题干
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
想法
dfs加回溯剪枝
设dfs(int cur,int n,int k){
表示从cur位置到n,要完成k个
如果
tem.size()+(n-cur+1)<k)
显然无论如何都完成不了,就剪枝
其中tem是找寻答案过程里的中间容器
Java代码
class Solution {
List<Integer> tem=new ArrayList<>();
List<List<Integer>> ans=new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
dfs(1,n,k);
return ans;
}
public void dfs(int cur,int n,int k){
if (tem.size() + (n - cur + 1) < k) {
return;
}
if(tem.size()==k){
ans.add(new ArrayList<Integer>(tem));
return;
}
if(cur==n+1){
return;
}
tem.add(cur);
dfs(cur+1,n,k);
tem.remove(tem.size()-1);
dfs(cur+1,n,k);
}
}