组合(回溯)
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例 2:
输入:n = 1, k = 1
输出:[[1]]
思路:转化为搜索树!!!
for (int i = startIndex; i <= n; i++) { // 控制树的横向遍历
path.push_back(i); // 处理节点
backtracking(n, k, i + 1); // 递归:控制树的纵向遍历,注意下一层搜索要从i+1开始
path.pop_back(); // 回溯,撤销处理的节点
}
public class Combine {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();//存放组合
public List<List<Integer>> combine(int n,int k){
combineHelper(n,k,1);
return result;
}
public void combineHelper(int n,int k,int startIndex){
//终止条件
if (path.size() == k){
result.add(new ArrayList<>(path));
return;
}
//递归和遍历
for (int i = startIndex;i<= n;i++){
path.add(i);
combineHelper(n,k,i+1);
path.removeLast();
}
}
}
思路:
转化为二叉搜索树,
然后将遍历,递归
for循环负责对该层进行遍历
递归负责深度遍历