[Problem]
[Solution]
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]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
// select k number from [begin, end]
vector<vector<int> > combine(int begin, int end, int k){
vector<vector<int> > res;
// invalid
if(begin > end || k <= 0){
return res;
}
else{
// select or not select 'begin'
for(int i = 0; i <= 1; ++i){
// select and only select 'begin'
if(i == 1 && k == 1){
vector<int> tmpRes(1, begin);
// filter duplicates
if(find(res.begin(), res.end(), tmpRes) == res.end()){
res.push_back(tmpRes);
}
}
else{
// next recursion
vector<vector<int> > nextRes = combine(begin+1, end, k-i);
// combine result
for(int j = 0; j < nextRes.size(); ++j){
vector<int> tmpRes(i, begin);
for(int l = 0; l < nextRes[j].size(); ++l){
tmpRes.push_back(nextRes[j][l]);
}
// filter duplicates
if(find(res.begin(), res.end(), tmpRes) == res.end()){
res.push_back(tmpRes);
}
}
}
}
return res;
}
}
// select k number from [1, n]
vector<vector<int> > combine(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return combine(1, n, k);
}
};