算法学习day24
77. 组合
给定两个整数 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]]
回溯法
- 参考回溯法模板,横向循环,循环中嵌套递归(纵向)
- 剪枝条件
- 剪枝一般发生在循环条件里
- 本题中当剩余节点不满足所求节点个数就可以终止循环
- 例如n =4, k =3 ,开始条件为1,2才满足path中可以取到三个数字,即
i<=(n - (k-path.size()) + 1)
- 例如n =4, k =3 ,开始条件为1,2才满足path中可以取到三个数字,即
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
combine(n, k, 1);
return res ;
}
public void combine(int n , int k , int start){
//终止条件 路径中存在k个数字
if(path.size() == k){
res.add(new ArrayList<Integer>(path));
return ;
}
//单层递归逻辑,横向循环每个节点1~n
for(int i = start ; i<= n - (k-path.size())+1 ; i++){
path.add(i);
combine(n,k,i+1);
path.removeLast();
}
}
}