zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Scale-Invariant Error
    Regularizing Deep Networks with Semantic Data Augmentation
    BBN: Bilateral-Branch Network with Cumulative Learning for Long-Tailed Visual Recognition
    2021.5.17
    2021.5.14
    2021.5.13
    2021.5.12
    2021.5.8
    2021.5.7 团队冲刺第十天
    2021.5.6 团队冲刺第九天
  • 原文地址:https://www.cnblogs.com/xiaolu266/p/7142014.html
Copyright © 2011-2022 走看看