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], ]
Subscribe to see which companies asked this question
static int m[100];
static int kk;
class Solution {
public:
void backtrack(vector<vector<int>>& result,vector<int>& temp,const int &n,int t)
{
if(temp.size()==kk)
{
result.push_back(temp);
return ;
}
else
{
for(int i=t+1;i<=n;++i)
{
if(m[i]==0)
{
m[i]=1;
temp.push_back(i);
backtrack(result,temp,n,i);
m[i]=0;
temp.pop_back();
}
}
return ;
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
vector<int> temp;
kk=k;
for(int i=1;i<=n;++i)
{
m[i]=1;
temp.push_back(i);
backtrack(result,temp,n,i);
m[i]=0;
temp.pop_back();
}
return result;
}
};