给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
最容易想到的应该是回溯,更多题目思路及代码见:https://github.com/CallmeZhouxiaolun/leetcode/tree/master/ordered/71to80
class Solution {
public:
vector> combine(int n, int k) {
vector> res;
vector cb;
backtracking(res, cb, n, k,1);
return res;
}
void backtracking(vector>& res, vector& cb, int n, int k, int c){
if(cb.size() == k){
res.push_back(cb);
return;
}
for(int i=c; i<=n; i++){
cb.push_back(i);
backtracking(res, cb, n, k, i+1);
cb.pop_back();
}
}
};
后来看到大佬的做法,有迭代方法,
class Solution {
public:
vector> combine(int n, int k) {
vector> res;
vector cb;
backtracking(res, cb, n, k,1);
return res;
}
void backtracking(vector>& res, vector& cb, int n, int k, int c){
if(cb.size() == k){
res.push_back(cb);
return;
}
for(int i=c; i<=n; i++){
cb.push_back(i);
backtracking(res, cb, n, k, i+1);
cb.pop_back();
}
}
};