Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
recursive
In this problem, we will use recursive function recur that will recursively call itself with different **starting position ** and push the current result to solution when the current result’s size is k.
For n = 3
recur[] start = 0
/ | \
recur[1], start = 1 recur[2], start = 2 recur[3], start = 3
/ \ |
r[1, 2] s=2 r[1,3] s = 3 r[2,3] s=3
When each recursive call is finished, we pop the res vector so it will resort to what res was before the call and avoid repeatedly allocate vectors.
class Solution {
public:
/**
recusrive funtion recur(partialConb, input) will call
**/
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> sol;
vector<int> res;
recurse(res, 0, k,n, sol);
return sol;
}
void recurse(vector<int>& res, int start, int k, int n, vector<vector<int>>& sol){
if(res.size() == k){
//cout<<"here with"<< res[0] <<res[1]<<"\n";
sol.push_back(res);
return;
}
for(int i = start; i < n; i ++){
//cout<<"pushing "<<i + 1<< "on size"<<res.size()<<"\n";
res.push_back(i + 1);
recurse(res, i + 1, k, n, sol);
res.pop_back();
//cout<<"after pop"<<res.size()<<"is size\n";
}
}
};