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], ]
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > ret;
if(n < k) return ret;
vector<int> tmp;
iter(0, n, k, tmp, ret);
return ret;
}
void iter(int num, int &maxNum, int k, vector<int> tmp, vector<vector<int> > &ret) {
if(k == 0) {
ret.push_back(tmp);
return;
}
if(k > 0) {
for(int i = 1; i <= maxNum - num; ++i) {
tmp.push_back(num+i);
iter(num+i, maxNum, k-1, tmp, ret);
tmp.pop_back();
}
}
}
};
歡迎關注微信公衆號——計算機視覺: