77.组合
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合
第一次做回溯+剪枝 参考题解:liweiwei1419
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if(k<=0||k>n)
return res;
Deque<Integer> path = new ArrayDeque<>();
dfs(n,k,1,path,res);
return res;
}
public void dfs(int n,int k,int begin,Deque<Integer> path,List<List<Integer>> res){
if(path.size()==k){
res.add(new ArrayList<>(path));
}
//循环遍历
//每次循环向path里添加i,若path.szie()==k,add到res
for(int i=begin;i<=n;i++){
path.addLast(i);
dfs(n,k,i+1,path,res);
//深度优先遍历有回头的过程,因此递归之前做了什么,递归之后需要做相同操作的逆向操作
path.removeLast();
}
}
}

浙公网安备 33010602011771号