132. Palindrome Partitioning II

Posted wz30

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了132. Palindrome Partitioning II相关的知识,希望对你有一定的参考价值。

dp or memo recursion

1. dp formulation

2. ispalindrome based on the nature structure

 

class Solution {
    //optimal problem dp: how to divide into differern subsets
    //dp = min ();//how many cuts, dp[i][j] dp[i-1][j+1]
    //or mem recursive 
    public int minCut(String s) {
       int n = s.length();
        if(n==0) return 0;
        boolean[][] dp = new boolean[n+1][n+1];//0 to n-1
        //preprocessing the string with dp[i][j] //check the   []
        //given fixed steps, check the palindrome*
        for(int step = 0; step < n;step++){
            for(int i = 0; i+step<n; i++){
                if(s.charAt(i)==s.charAt(i+step)){
                    if(step <=2 || dp[i+1][i+step-1]){
                        dp[i][i+step] = true;
                        dp[i+step][i] = true;
                    }
                }
            }
        }
        //cut[i][j] : minimal cut from i to j
        //initialize 
        int[][] cut = new int[n+1][n+1];
        for(int i = 0 ;i < n;i++){
            for(int j = i; j<n; j++){
                cut[i][j] = j-i;
            }    
        }
        //cut[0][j] = min(cut[0][j], cut[0][i-1] +1(if dp[i][j]==true))
        for(int j = 0; j<n; j++){
            for(int i = 1; i<=j; i++){
               if(dp[0][j]){
                   cut[0][j] = 0;
               }else if(dp[i][j]){
                   cut[0][j]= Math.min(cut[0][j], cut[0][i-1]+1);
               }
            }
        }
        return cut[0][n-1];
    }
}

 

以上是关于132. Palindrome Partitioning II的主要内容,如果未能解决你的问题,请参考以下文章

131. 132. Palindrome Partitioning *HARD* -- 分割回文字符串

132. Palindrome Partitioning II

leetcode 132 Palindrome Partitioning II

lintcode-medium-Palindrome Partition II

132. Palindrome Partitioning II

Leetcode 132. Palindrome Partitioning II