77 Combinations
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],
]
Solution-recursive
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
vector<int> tmp;
if ( n < k or k == 0 ) {
result.push_back(tmp);
return result;
}
vector<vector<int>> help1 = combine(n-1, k-1);
vector<vector<int>> help2 = combine(n-1, k);
for ( int i = 0; i <= help1.size()-1; i++ ) {
tmp = help1[i];
tmp.push_back(n);
result.push_back(tmp);
}
for ( int i = 0; i <= help2.size()-1; i++ ) {
tmp = help2[i];
if ( tmp.size() != 0 ) result.push_back(help2[i]);
}
return result;
}
};
Solution-recusive, V2
class Solution {
public:
void help(int n, int i0, int k, vector<int> curr, vector<vector<int>>& res) {
if ( n-i0+1 < k ) return;
if ( k == 0 ) {res.push_back(curr); return;}
if ( i0 == n+1 ) return;
help(n, i0+1, k, curr, res);
curr.push_back(i0);
help(n, i0+1, k-1, curr, res);
return;
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> curr;
help(n, 1, k, curr, res);
return res;
}
};