Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
这道题和剑指Offer中的全排列问题有点类似,主要就是回溯法,深度优先选择组合,到达终止条件后,返回到历史的解决方案中进行下一个搜索,这里我用递归实现,代码如下:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
if(n==0||k==0||n<k) return ans;
for(int i=1;i<=n;i++){
vector<int> f_v;
f_v.push_back(i);
combine(n,k-1,i+1,ans,f_v);
}
return ans;
}
void combine(int n,int k,int index,vector<vector<int>>& ans,vector<int>& t_ans){
if(k==0){
ans.push_back(t_ans);
return;
}
for(int i=index;i<=n;i++){
t_ans.push_back(i);
combine(n,k-1,i+1,ans,t_ans);
t_ans.pop_back();
}
}
};