「程式碼隨想錄演算法訓練營」第二十天 | 回溯演算法 part2

云雀AC了一整天發表於2024-07-25

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;
    }
};

相關文章