leetcode77. 组合 medium
题目描述:
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
解题思路:
回溯again
dfs函数 中的k表示剩余没搞好的数,index表示还这次的备胎从哪开始
- 注意组合和排列的区别,对排列来说,[1, 2] 和 [2, 1] 是不同的排列,对组合来说是同一个组合;
所以我们为了避免这样的重复,假设我们当前枚举到了2(i),我们下一次必须从3(i+1)开始枚举,不能从1开始
代码:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
if(n<1 || k<1 || n<k)
return {};
vector<int> out;
vector<vector<int>> res;
dfs(n,k,1,out,res);
return res;
}
void dfs(int n, int k,int index,vector<int> &out,vector<vector<int>> &res){ //k表示剩余没搞好的数,index表示还这次的备胎从哪开始
if(k==0){
res.push_back(out);
return;
}
if(k>(n-index+1))
return; // 剪枝 剪不剪都ok
for(int i=index;i<=n;++i){
out.push_back(i);
dfs(n,k-1,i+1,out,res);
out.pop_back();
}
}
};