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:
在leetcode做了很多类似的题目,用递归的思想去解决就可以了。
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
_docombine(n,k,1);
return rst;
}
private:
vector<vector<int>> rst;
vector<int> temp;
void _docombine(int n,int k,int start){
if(temp.size()==k){
rst.push_back(temp);
}
else{
for(int i=start;i<=n;i++){
temp.push_back(i);
_docombine(n,k,i+1);
temp.pop_back();
}
}
}
};