39. 组合总和
文档讲解:代码随想录.组合总和
视频讲解:带你学透回溯算法-组合总和(对应「leetcode」力扣题目:39.组合总和)| 回溯法精讲!
状态:已完成
代码实现
class Solution {private:vector<vector<int>> result;vector<int> path;void backtracking(vector<int> candidates, int target, int sum,int start_index) {if (sum > target) {return;}if (sum == target) {result.push_back(path);}for (int i = start_index; i < candidates.size(); i++) {path.push_back(candidates[i]);sum += candidates[i];backtracking(candidates, target, sum, i);sum -= candidates[i];path.pop_back();}}public:vector<vector<int>> combinationSum(vector<int>& candidates, int target) {result.clear();path.clear();backtracking(candidates, target, 0, 0);return result;}
};
心得体会
1.回溯思想的理解更加深入,逐渐上手
40.组合总和II
文档讲解:代码随想录.组合总和II
视频讲解:回溯算法中的去重,树层去重树枝去重,你弄清楚了没?| LeetCode:40.组合总和II
状态:已完成
代码实现
class Solution {
private:vector<vector<int>> result;vector<int> path;void backtracking(vector<int>& candidates, int target, int sum,int start_index, vector<bool>& used) {if (sum == target) {result.push_back(path);return;}for (int i = start_index;i < candidates.size() && sum + candidates[i] <= target; i++) {if (i > 0 && candidates[i] == candidates[i - 1] &&used[i - 1] == false) {continue;}sum += candidates[i];path.push_back(candidates[i]);used[i] = true;backtracking(candidates, target, sum, i+1, used);used[i] = false;sum -= candidates[i];path.pop_back();}}public:vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {vector<bool> used(candidates.size(), false);result.clear();path.clear();sort(candidates.begin(), candidates.end());backtracking(candidates, target, 0, 0, used);return result;}
};
心得体会
1.思维逻辑有些混乱,总感觉有些地方理解不到位,暂时先按照答案输入了一遍
131.分割回文串
文档讲解:代码随想录.分割回文串
视频讲解:带你学透回溯算法-分割回文串(对应力扣题目:131.分割回文串)| 回溯法精讲!
状态:未完成,后续再补充