题目描述:
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],
]
解题思路:
深度优先搜索,k层深度,不够k层就回溯
代码:
class Solution {
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > res;
int a[k];
dfs(res,a,0,k,0,n);
return res;
}
void dfs(vector<vector<int> > &res,int a[],int depth,int k,int cur,int n)
{
if(depth == k){
vector<int> temp;
for(int i = 0; i < k; i++)
temp.push_back(a[i]);
res.push_back(temp);
return ;
}
for(int i = cur;i < n;i++){
if(n - cur < k - depth)
return ; //剩下的数凑不齐k个,回溯
a[depth] = i + 1;
dfs(res,a,depth + 1,k,i + 1,n);
}
}
};
代码运行结果: