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], ]
要求的是所有可能的组合,并且不能重复,[1,2], [2,1]算是一个,那么,我们就让每一条可能的答案都是递增的。我的思路是从当前的这条记录找第一个小于n并且在它之后的位数小于当前可放置的数的个数。
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > results;
if(n < k) return results;
vector<int> current;
for(int ii = 1; ii <= k; ii ++) {
current.push_back(ii);
}
while(1) {
results.push_back(current);
int lessthan_n = k - 1;
while(lessthan_n >= 0) {
if(current[lessthan_n] < n && k - lessthan_n <= n - current[lessthan_n])
break;
lessthan_n --;
}
if(lessthan_n < 0)
break;
current[lessthan_n] ++;
for(int ii = lessthan_n; ii < k; ii ++) {
current[ii] = current[lessthan_n] + ii - lessthan_n;
}
}
return results;
}
};