代码随想录 Leetcode131. 分割回文串

题目:

代码随想录 Leetcode131. 分割回文串_第1张图片


代码(首刷看解析 2024年2月3日):

class Solution {
public:
    vector> res;
    vector path;
    bool isPalindrome(const 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(const string& s, int startIndex) {
        if (startIndex >= s.size()) {
            res.push_back(path);
            return;
        }
        for (int i = startIndex; i < s.size(); ++i) {
            if (isPalindrome(s, startIndex, i)) {
                string str = s.substr(startIndex, i + 1 - startIndex);
                path.push_back(str);
            } else {
                continue;
            }
            backtracking(s, i + 1);
            path.pop_back();
        }
        return;
    }
    vector> partition(string s) {
        if (s.size() == 0) return res;
        backtracking(s, 0);
        return res;
    }
};

你可能感兴趣的:(#,leetcode,---medium,前端,算法,javascript)