回溯在这道题中等价于for循环的嵌套, 每深入一层递归等价于每深入一层for循环, 循环层数是参数, 所以无法直接写循环嵌套
力扣77. 组合
class Solution {
public List<Integer> path = new ArrayList<>();
public List<List<Integer>> result = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backTracking(n, k, 1);
return result;
}
public void backTracking(int n, int k, int startId) {
if(path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for(int i = startId; i <= n; i++) {
path.add(i);
backTracking(n, k, i + 1);
path.removeLast();
}
}
}