class Solution {
//using recurrence to get these combinations
public:
vector<vector<int> > combine(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> temp;
vector<vector<int> > ans;
combine_rec(ans , temp , n , k , 1);
return ans;
}
void combine_rec(vector<vector<int> > &ans , vector<int>& temp , int n , int k , int index)
{
if (k == 0)
ans.push_back(temp);
else if (k > 0 && index <= n)
{
temp.push_back(index);
combine_rec(ans , temp , n , k-1 , index+1);
temp.pop_back();
combine_rec(ans , temp , n , k , index+1);
}
}
};
second time
class Solution {
public:
void combineUtil(int n, int k, int curIdx, vector<int>& curPath, vector<vector<int> >& allPath)
{
if(curPath.size() == k)
{
allPath.push_back(curPath);
return;
}
if(curIdx >= n+1) return;
combineUtil(n, k, curIdx+1, curPath, allPath);
curPath.push_back(curIdx);
combineUtil(n, k, curIdx+1, curPath, allPath);
curPath.pop_back();
}
vector<vector<int> > combine(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> curPath;
vector<vector<int> > allPath;
combineUtil(n, k, 1, curPath, allPath);
return allPath;
}
};