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], ]
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int>>res;
vector<int>ans;
build(1,n,k,ans,res);
return res;
}
void build(int num,int n,int k,vector<int>&ans,vector<vector<int>>&res)
{
if(k==0){
res.push_back(ans);
return;
}
if(num>n)return;
ans.push_back(num);
build(num+1,n,k-1,ans,res);
ans.pop_back();
build(num+1,n,k,ans,res);
}
};
本文介绍了一种使用递归算法生成所有可能的k个数字组合的解决方案,这些数字来自1到n的整数集合。通过一个具体的例子展示了当n为4且k为2时,所有可能的组合。

270

被折叠的 条评论
为什么被折叠?



