1. 程式人生 > >LeetCode:132. Palindrome Partitioning II

LeetCode:132. Palindrome Partitioning II

題目是這樣:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s. 例子: Input: “aab” Output: 1 Explanation: The palindrome partitioning [“aa”,“b”] could be produced using 1 cut.

題目大意就是給一個字串,問最少對它切割幾次,使得到的每個子串都是迴文子串。 這題明顯得用動態規劃。難點依然在於如何定義狀態。 這題的狀態定義比較特殊,需要定義兩個狀態,且第二個狀態依賴於第一個狀態求解: pal[i][j]:表示s[i…j]能否形成迴文子串。 d[i]:表示對於s[i…,n-1]的minCut。 狀態轉移方程是: pal[i][j]=true, 如果 s[i] == s[j] && (j-i<2 || pal[i+1][j-1])

當pal[i][j] ==true: 如果 j=n-1,d[i] = 0;否則,d[i] = min(1+d[j+1])

程式碼是:

class Solution {
public:
    int minCut(string s) {
        if (s.empty())
            return 0;
        int n = s.length();
        vector<vector<bool>> pal(n, vector<bool>(n, false));
        vector<int> d(n, 0);
        for (int i = n-1; i >= 0; --i){
            d[i] = n-1-i;
            for (int j = i; j < n; ++j) {
                if (s[i] == s[j] && (j-i<2 || pal[i+1][j-1])) {//測試是否是迴文的聰明方法,不是笨方法
                    pal[i][j] = true;
                    if (j == n-1)
                        d[i] = 0;
                    else if(d[i] > d[j+1]+1)
                        d[i] = d[j+1]+1;
                }
            }
        }
        return d[0];
    }
};