LeetCode-Palindrome Partitioning II[dp]

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.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

 

标签: Dynamic Programming

分析:动态规划,设f[i,j]表示区间[i,j]的最少cut数,所以状态方程为:

      f[i,j]=min(f[i,k],f[k+1,j])   (i<=k<=j);

在二维dp的基础上在优化成一维dp:

设f[i]表示i到len-1的最少cut数,所以状态方程为;

      f[i]=min(f[i],f[j+1]+1)   (s[i...j]为回文字符串&&i<=j<<len-1)

判断s[i...j]是否为回文字符串也可以用动态规划,可以新建boolean数组isPal[len][len],isPal[i][j]表示s[i][j]为回文字符串;

参考代码:

 1 public class Solution {
 2     public int minCut(String s) {
 3         int len=s.length();
 4         int cutnum[]=new int[len+1];
 5         boolean isPal[][]=new boolean[len][len];
 6         for(int i=0;i<=len;i++){
 7             cutnum[i]=len-1-i;//先假设i到len-1间每个字符都cut
 8         }
 9         for(int i=len-1;i>=0;i--){
10             for(int j=i;j<len;j++){
11                 if(s.charAt(i)==s.charAt(j)&&(j-i<2||isPal[i+1][j-1])){
12                     isPal[i][j]=true;
13                     cutnum[i]=Math.min(cutnum[i], cutnum[j+1]+1);
14                 }
15             }
16         }
17         return cutnum[0];
18     }
19 }

 

posted @ 2017-07-09 17:01  Little_Lu  阅读(137)  评论(0编辑  收藏  举报