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],
]
思路:深度优先搜索。这是一个典型的dfs题,排列组合问题基本都是,构造递归函数,满足条件时返回,注意回溯。
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>>result;
vector<int>path;
dfs(result,path,1,n,k);
return result;
}
void dfs(vector<vector<int>>&result,vector<int>&path,int start,int n,int k){
if(path.size()==k){
result.push_back(path);
return;
}
for(int i=start;i<=n;i++){
path.push_back(i);
dfs(result,path,i+1,n,k);
path.pop_back();
}
}
};