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], ]
Difficulty:Medium
简单的回溯。
void gen(vector<vector<int> >& ans,vector<int>& v,int dep,int n,int num){
if(dep<=0||num>n)
return;
vector<int> v1 = v;
while(num<=n-dep+1)
{
v1.push_back(num);
if(dep==1)
ans.push_back(v1);
else
gen(ans,v1,dep-1,n,num+1);
v1 = v;
num++;
}
return;
}
vector<vector<int> > combine(int n, int k) {
vector<int> v;
vector<vector<int> > ans;
gen(ans,v,k,n,1);
return ans;
}