题目:
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> > sumv;
if(k < 1 || k > n)
return sumv;
vector<int> tempv;
//comb1(sumv,tempv,n,k,1);
comb2(sumv,tempv,n,k,1);
return sumv;
}
/* void comb1(vector<vector<int> >&sumv, vector<int>& tempv,int n,int k,int start)
{
for(int i= start; i <= n;i++)
{
tempv.push_back(i);
if(tempv.size() == k)
{
sumv.push_back(tempv);
tempv.pop_back();
continue;
}
if(i < n) comb(sumv,tempv,n,k,i+1);
tempv.pop_back();
}
}
*/
void comb2(vector<vector<int> >&sumv, vector<int>& tempv,int n,int k, int start)
{
if(k==0)
{
sumv.push_back(tempv);
return ;
}
for(int i = start; i <= n; i++)
{
tempv.push_back(i);
comb2(sumv, tempv,n,k-1,i+1);
tempv.pop_back();
}
}
};