Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
题目链接:https://leetcode-cn.com/problems/combinations/
思路
法一:回溯法
这道题有一个去重的小规律:固定一个数a,找第二个结对的数b时只找比自己大的数。
本代码的递归停止条件是k=1。
在可行情况下,要么在k==1时返回新建的结果表,要么在k>1时返回更新后的递归结果;只有在无法进入for循环时会返回空结果,此时说明该条路不是可行情况,直接跳过剪枝。
另一个剪枝的判定:当剩余数字的数量比需求的少时,也是不可行的,因此可以直接剪掉;比如上图的最右边4分支。这一个判定写在了for循环里i的上界。
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
if(n<=0 || n<k) return res;
return trace(n, k, 0);
}
vector<vector<int>> trace(int n, int k, int last){
vector<vector<int>> res;
for(int i=last+1; i<=n-k+1; ++i){
if(k==1){
vector<int> tmp = {i};
res.push_back(tmp);
}else{
auto tmp = trace(n, k-1, i);
if(tmp.size()<=0) continue;
for(int j=0; j<tmp.size(); ++j){
tmp[j].push_back(i);
}
res.insert(res.begin(), tmp.begin(), tmp.end());
}
}
return res;
}
};
法二:二进制
这是分享看来的方法:https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode/
没细看,待补全。