77. Combinations
problem description
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]algorithm thought
code
algorithm analysis
Last updated
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]Last updated
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp;
helper(res,tmp,n,k,1);
return res;
}
void helper(vector<vector<int>>& res,vector<int>&tmp,int n,int k,int pos){
if(tmp.size()==k){
res.push_back(tmp);
return;
}
for(int i=pos;i<=n;++i){
tmp.push_back(i);
helper(res,tmp,n,k,i+1);
tmp.pop_back();
}
}
};