题目:
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], ]即从n个数中取出k个,总共有多少种组合,很简单的递归搞定。
vector<vector<int> > comb;
void Comb(int begin, int n, int k, vector<int> vint)
{
if(k==0)
{
comb.push_back(vint);
return;
}
for(int i=begin; i<=n-k+1; i++ )
{
vint.push_back(i);
Comb(i+1, n, k-1, vint);
vint.pop_back();
}
return;
}
vector<vector<int> > combine(int n, int k)
{
vector<int> vint;
Comb(1, n,k, vint) ;
return comb;
}
扩展:实现n个数的全部组合,如n=3,得到{[1,2,3],[1,2],[1],[2,3],[2],[3]}。
vector<vector<int> > comb;
void combinen(int begin, int n, vector<int> vint)
{
if(begin > n)
{
if(vint.size()>0) comb.push_back(vint);
return;
}
for(int i=begin; i<=n+1; i++ ) <span style="font-family: 'Microsoft YaHei';">//这里多加一个n,是为了push一个数的情况</span>
{
if(i<=n) vint.push_back(i);
combinen(i+1, n, vint); //指到下一个元素,不能重复
if(i<=n) vint.pop_back();
}
return;
}