backtracking 回溯

77 阅读1分钟

今日鸡汤:要在山顶上哭,不要在到达的路上哭

  1. leetcode 77 寻找组合数

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

 

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

image.png 其中下面的for循环是横向遍历,而递归backtracking是纵向遍历

剪枝的过程很重要:

  1. k - path.size() 还剩多少个元素
  2. n - (k - path.size()) + 1 至多从哪里开始搜索
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    public void backtracking(int n, int k, int startIndex) {
        if(k == path.size()) {
            res.add(new ArrayList<>(path));
            return;
        }
        // k - path.size() 还剩多少个元素
        // n - (k - path.size()) + 1 至多从哪里开始搜索
        for(int i = startIndex; i <= n - (k - path.size()) + 1; i++) {
            path.add(i);
            backtracking(n, k, i+1);
            path.removeLast();
        }
    }
    public List<List<Integer>> combine(int n, int k) {
        backtracking(n, k, 1);
        return res;
    }
}