1. 程式人生 > >【DP】迴文的最小分割數

【DP】迴文的最小分割數

題目描述

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.
For example, given s = "aab",

Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

動態規劃總是練不好,強行遞迴每次又都超時,真的是煩。

思路:從頭開始,第一個元素單獨切割一定是迴文。

dp[i]表示以第i個字元結尾分割成迴文組的最小分割數。

isParli[i][j]表示從第i個字元到第j個字元能否構成迴文。

isParli[i][j] = ((charAt(i) == charAt(k)) && (i - k < 2 || isParli[i - 1][k + 1]));

return最後一個dp[]即為結果。

public class Solution {
    
    public int minCut(String s) {
        int [] dp = new int [s.length() + 1];
        boolean [][] isParli  = new boolean [s.length() + 1][s.length() + 1];
        dp[0] = -1;
        
        for(int i = 2; i <= s.length(); ++i)
            dp[i] = Integer.MAX_VALUE;
        
        for(int i = 1; i <= s.length(); ++i){
            for(int k = 1; k <= i; ++k){
                if((i - k < 2 || isParli[i - 1][k + 1]) && s.charAt(i - 1) == s.charAt(k - 1)){
                    isParli[i][k] = true;
                    dp[i] = Math.min(dp[i],dp[k - 1] + 1);
                }
            }
        }
        return dp[s.length()];
    }
    
}