回溯算法

leetcode:131 分割回文串

问题

说实话,状态学了回溯,感觉已经懂了但是,今天这是搞笑

代码

直接上代码
先上图,理解这个startIndex

class Solution {
private:
    vector<vector<string>> result;
    vector<string> str; 
    bool isPalindrome(const string& str1, int start, int end){
       while (start < end) {
            if (str1[start] != str1[end]) {
                return false;
            }
            start++;
            end--;
        }
        return 1;

    }
    void backtracking(string& s, int startIndex){
        if (startIndex >= s.size()) {
            result.push_back(str);
            return;
        }
        for (int i = startIndex; i < s.size(); i++) {
            if (isPalindrome(s,startIndex, i)) { // 个人觉得最难的是这个startIndex ,针对不好控制
                str.push_back(s.substr(startIndex, i - startIndex  + 1 ));
            } else continue;
            backtracking(s,i + 1);
            str.pop_back();
        }
    }
public:
    vector<vector<string>> partition(string s) {
        backtracking(s,0);
        return result;
    }
};
posted @ 2023-03-05 09:38  壹剑霜寒十四州  阅读(7)  评论(0编辑  收藏  举报