Leetcode 132. 分割回文串 II

和131类似,注意用dp剪枝,

class Solution {
public:
    int ans, tmp;
    vector<int> dp;
    string str, x, ss;
    bool is_P() {
        int i = 0, j = str.size() - 1;
        while (i < j) {
            if (str[i] == str[j]) ++i, --j;
            else return false;
        }
        return true;
    }
    void dfs(string &s, int index, int &c) {
        if (tmp >= ans) return;
        if (index == s.size() - 1) {
            str += s.back();
            if (is_P()) ans = min(ans, tmp);
            str.pop_back();
            return;
        }
        str += s[index];
        if (is_P())
            ans = min(ans, tmp + 1 + dp[index + 1 + c]);
        dfs(s, index + 1, c);
        str.pop_back();
    }
    int minCut(string s) {
        if (s.empty()) return ans;
        dp.assign(s.size(), 0);
        for (int k = s.size() - 1; k >= 0; --k)
            ss = string(s, k, 9999), tmp = 0, ans = ss.size() - 1, dfs(ss, 0, k), dp[k] = ans;
        return ans;
    }
};

你可能感兴趣的:(Leetcode 132. 分割回文串 II)