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 {
public:
vector<vector<int> > com(int begin, int end, int k){
vector<vector<int> > res;
if(k > 0 && begin <= end){
//cout << "begin=" << begin << ", end=" << end << ", k=" << k << endl;
vector<vector<int> >::iterator i;
vector<int>::iterator j;
// contains 'begin'
if(k == 1){
vector<int> r;
r.push_back(begin);
res.push_back(r);
}
else{
vector<vector<int> > r1 = com(begin + 1, end, k - 1);
for(i = r1.begin(); i != r1.end(); ++i){
vector<int> r;
r.push_back(begin);
for(j = (*i).begin(); j != (*i).end(); ++j){
r.push_back(*j);
}
res.push_back(r);
}
}
// not contains 'begin'
vector<vector<int> > r2 = com(begin + 1, end, k);
for(i = r2.begin(); i != r2.end(); ++i){
vector<int> r;
for(j = (*i).begin(); j != (*i).end(); ++j){
r.push_back(*j);
}
res.push_back(r);
}
}
return res;
}
vector<vector<int> > combine(int n, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res = com(1, n, k);
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客