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], ]
Have you met this question in a real interview?
Yes
No
class Solution {
vector<bool> flag;
vector<vector<int> > ret;
void dfs(int n, int k, int index, int count){
if(k==count){
vector<int> ans;
for(int i=1;i<=n;i++)
if(flag[i])
ans.push_back(i);
ret.push_back(ans);
return;
}
if(index>=n) //注意判断,不然越界
return;
flag[index+1] = true;
dfs(n, k, index+1, count+1);
flag[index+1] = false;
dfs(n, k, index+1, count);
}
public:
vector<vector<int> > combine(int n, int k) {
for(int i=0;i<=n;i++)
flag.push_back(false);
dfs(n,k,0,0);
return ret;
}
};