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> > ivecArray;
vector<int> ivec;
if (n < k)
return ivecArray;
findcombine(1, n, k, ivecArray, ivec);
return ivecArray;
}
void findcombine(int left, int right, int k,
vector<vector<int> > &ivecArray, vector<int> ivec) { //注意ivec不是引用
if (k <= 0) {
ivecArray.push_back(ivec);
return;
}
else {
if (right - left + 1 >= k) {
findcombine(left + 1, right, k, ivecArray, ivec);
ivec.push_back(left);
findcombine(left + 1, right, k - 1, ivecArray, ivec);
}
}
}
};
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > ivecArray;
vector<int> ivec;
if (n < k)
return ivecArray;
findcombine(1, n, k, ivecArray, ivec);
return ivecArray;
}
void findcombine(int start, int n, int k,
vector<vector<int> > &ivecArray, vector<int> &ivec) {
if (ivec.size() == k) {
ivecArray.push_back(ivec);
return;
}
for (int i = start; i <= n; i++) {
ivec.push_back(i);
findcombine(i + 1, n, k, ivecArray, ivec);
ivec.pop_back();
}
}
};