学习要点
学习回溯思想,学习回溯技巧;大家应当先看一下下面这几道题
- leetcode:46. 全排列-CSDN博客
- leetcode:78. 子集-CSDN博客
- leetcode:90. 子集 II-CSDN博客
题目链接
77. 组合 - 力扣(LeetCode)
题目描述
解法:回溯
class Solution {
public:vector<vector<int>> ret;vector<int> path;void dfs(int n, int k,int pos){if(path.size() == k){ret.push_back(path);return;}for(int i = pos; i<=n; i++){path.push_back(i);dfs(n,k,i+1);path.pop_back();}}vector<vector<int>> combine(int n, int k) {ret.clear(); path.clear();dfs(n,k,1);return ret;}
};
解析
- 先添加有1的
- 再添加有2,但是没有1的
- 再添加有3,但是没有1和2的
- 以此类推