题目连接:Leetcode 077 Combinations
解题思路:DFS,每层参数包括当前使用过数字的起始位置start,总共的数字个数end,已选择数字的个数dep。每层遍历选择一个数,进入下一层搜索。
class Solution {
public:
void dfs(int start, int end, int dep, vector<int> cur, vector<vector<int>>& ans) {
if (dep == 0) {
ans.push_back(cur);
return;
}
for (int i = start; i <= end; i++) {
vector<int> tmp = cur;
tmp.push_back(i);
dfs(i + 1, end, dep - 1, tmp, ans);
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> cur;
dfs(1, n, k, cur, ans);
return ans;
}
};