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> > Martrix;
vector<int> temp;
for( int i = 0;i < k;++i )
temp.push_back(i+1);
Martrix.push_back(temp);
if( n == k ) return Martrix;
do{
int t = k - 1,r = n;
while( temp[t] == r ) {
t--;
r--;
}
temp[t]++;
for( int i = t + 1;i < k;++i )
temp[i] = temp[i-1] + 1;
Martrix.push_back(temp);
}while( temp[0] != n - k + 1 );
return Martrix;
}
};
没什么独创的,就是组合问题的输出,上面的算法只是需要注意一下n == k时应该直接在存入全序列后即返回,否则在内部while循环会陷入死循环(或者可以修改下内部循环则可以只需要一个return语句即可)。