77. 组合
中等
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtraking(n,k,1);
return res;
}
private void backtraking(int n, int k, int index){
if(path.size()==k){
res.add(new ArrayList<>(path));
return;
}
for(int i=index;i<=n;i++){
path.add(i);
backtraking(n,k,i+1);
path.removeLast();
}
}
}
1.注意题目要求的返回答案类型,这里是List<List<Integer>>
2.回溯的步骤,一般再递归后面,体现再path.removeLast();
3. path 的横向for 循环,注意i+1 传入递归参数
4.明天进阶剪枝