「代码随想录算法训练营」第二十天 | 回溯算法 part2

39. 组合总和

题目链接:https://leetcode.cn/problems/combination-sum/
题目难度:中等
文章讲解:https://programmercarl.com/0039.组合总和.html
视频讲解:https://www.bilibili.com/video/BV1KT4y1M7HJ
题目状态:久违的通过!

思路:

使用回溯模板,在单层循环时判断当前数组值是否大于目标值,若大于,直接跳过,其他思路就是和回溯模板中一样,直接看代码。

代码:

class Solution {
public:
    vector<vector<int>> res;
    vector<int> vec;
    void backtracking(vector<int> &candidates, int target, int startIndex) {
        if(target == 0) {
            res.push_back(vec);
            return;
        }
        for(int i = startIndex; i < candidates.size(); ++i) {
            if(candidates[i] > target)
                continue;
            vec.push_back(candidates[i]);
            target -= candidates[i];
            backtracking(candidates, target, i);
            vec.pop_back();
            target += candidates[i];
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        
        backtracking(candidates, target, 0);
        return res;
    }
};

剪枝优化后的代码:

class Solution {
private:
    vector<vector<int>> result;
    vector<int> path;
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {
        if (sum == target) {
            result.push_back(path);
            return;
        }

        // 如果 sum + candidates[i] > target 就终止遍历
        for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
            sum += candidates[i];
            path.push_back(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();
        sort(candidates.begin(), candidates.end()); // 需要排序
        backtracking(candidates, target, 0, 0);
        return result;
    }
};

40. 组合总和II

题目链接:https://leetcode.cn/problems/combination-sum-ii/
题目难度:中等
文章讲解:https://programmercarl.com/0040.组合总和II.html
视频讲解:https://www.bilibili.com/video/BV12V4y1V73A
题目状态:借助ChatGPT通过

思路:

在每层递归的时候,要确保当前递归的值和前一个递归的值不相等。因此需要首先对数组排序,之后在执行回溯三部曲。

代码:

class Solution {
public:
    vector<vector<int>> res;
    vector<int> vec;
    void backtracking(vector<int> &candidates, int target, int startIdx) {
        if(target == 0) {
            res.push_back(vec);
            return;
        }
        for(int i = startIdx; i < candidates.size(); ++i) {
            if(i > startIdx && candidates[i] == candidates[i - 1]) 
                continue;
            if(target < candidates[i]) 
                break;
            target -= candidates[i];
            vec.push_back(candidates[i]);
            backtracking(candidates, target, i + 1);
            target += candidates[i];
            vec.pop_back();
        }
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0);
        return res;
    }
};

131. 分割回文串

题目链接:https://leetcode.cn/problems/palindrome-partitioning/
题目难度:中等
文章讲解:https://programmercarl.com/0131.分割回文串.html
视频讲解:https://www.bilibili.com/video/BV1c54y1e7k6
题目状态:这题好难,看题解通过

思路:

通过回溯,每层分割是按照几个元素来分,每次分割后判断分割出来的元素是否是一个回文串,直接理解代码会更好理解一些。

代码:

class Solution {
public:
    vector<vector<string>> res;
    vector<string> vec;
    bool isLoop(string s, int start, int end) {
        for(int i = start, j = end; i < j; i++, j--)
            if(s[i] != s[j]) return false;
        return true;
    }
    void backtracking(string s, int startIdx) {
        if(startIdx >= s.size()) {
            res.push_back(vec);
            return;
        }
        for(int i = startIdx; i < s.size(); ++i) {
            if(isLoop(s, startIdx, i)) {
                string str = s.substr(startIdx, i - startIdx + 1);
                vec.push_back(str);
            } else {
                continue;
            }
            backtracking(s, i + 1);
            vec.pop_back();
        }
    }
    vector<vector<string>> partition(string s) {
        backtracking(s, 0);
        return res;
    }
};

热门相关:重生童养媳:枭宠不乖娇妻   隐婚365天:江少,高调宠!   来自异世界的诺诺   惹火小辣妻:老公,用力点   绝天武帝