1. 程式人生 > >【LeetCode】121.Palindrome Partitioning II

【LeetCode】121.Palindrome Partitioning II

題目描述(Hard)

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.

題目連結

https://leetcode.com/problems/palindrome-partitioning-ii/description/

Example 1:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

演算法分析

每次從i往右掃描,每找到一個迴文就算一次DP,可以轉換為f(i)=[i, n-1]之間的最小的cut數,n為字串長度,則狀態轉移方程為f(i)=min{f(j+1)+1},i\leq j< n。判斷[i,j]為迴文,每次從i到j比較太過於費時,可以定義狀態P[i][j]=true,如果[i,j]為迴文,那麼P[i][j]=str[i]==str[j] && P[i+1][j-1]。

提交程式碼:

class Solution {
public:
    int minCut(string s) {
        const int n = s.size();
        int f[n + 1];
        bool p[n][n];
        
        fill_n(&p[0][0], n * n, false);
        for (int i = 0; i <= n; ++i)
            f[i] = n - i - 1;
        
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i; j < n; ++j) {
                if (s[i] == s[j] && (j - i < 2 || p[i + 1][j - 1])) {
                    p[i][j] = true;
                    f[i] = min(f[i], f[j + 1] + 1);
                }
            }
        }
        
        return f[0];
    }
};