码迷,mamicode.com
首页 > 其他好文 > 详细

132. Palindrome Partitioning II

时间:2018-05-19 11:08:20      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:[]   span   ima   into   diff   length   boolean   initial   n+1   

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

标签:[]   span   ima   into   diff   length   boolean   initial   n+1   

原文地址:https://www.cnblogs.com/stiles/p/Leetcode132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!