一、问题描述
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], ]
二、思路
题目意思是求前n个数k个元素的子集,思路是递归求解。递归退出条件:当元素数k为0时,将当前的子集加入二维数组。
n - i + 1 >= k;
上面这个循环退出条件非常关键,保证我们可以选择的数必须大于或者等于k,很好理解,即如果小于k,我们就没办法挑出k个元素!!!
接着循环中对k -1个数进行递归,最后需要剔除当前子集中最后一个元素。
三、代码
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> vec;
vector<int> temp;
combineLoop(1, n, k, temp, vec);
return vec;
}
private:
void combineLoop(int begin,int n ,int k,vector<int> &temp, vector<vector<int>>& vec){
if(k == 0){
vec.push_back(temp);
return;
}
for(int i = begin; n - i + 1 >= k; ++i){
temp.push_back(i);
combineLoop(i + 1, n, k - 1, temp, vec);
temp.pop_back();
}
}
};