【题目描述】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开始的看个数的combination,之后再求以2开始的,以此类推,所以开始是对n个数做DFS, n-1个数做DFS…所以应该是对n(n-1)…*1做DFS. 在程序中,我们可以加一些剪枝条件来减少程序时间
【考查内容】数组,查找,深度搜索
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int>> ret;
if(n <= 0) //corner case invalid check
return ret;
vector<int> curr;
DFS(ret,curr, n, k, 1); //we pass ret as reference at here
return ret;
}
void DFS(vector<vector<int>>& ret, vector<int> curr, int n, int k, int level){
if(curr.size() == k){
ret.push_back(curr);
return;
}
if(curr.size() > k) // consider this check to save run time
return;
for(int i = level; i <= n; ++i){
curr.push_back(i);
DFS(ret,curr,n,k,i+1);
curr.pop_back();
}
}
};