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.

思路

1.用回溯,递归回溯超时

2.dp

这里需要两个dp状态数组

isPalin[i][j] = true表示字符串str.sub(i, j)为回文

递推关系式isPalin[i][j] = (str.charAt(i) == str.charAt(j) && j -i < 2) || (str.charAt(i) == str.charAt(j) && isPalin[i + 1][j - 1])

cuts[i]表示从第str.charAt(i)到str.length()需要多少cut。默认为每个字符都切一刀,即cuts[i] = str.length - i。递推关系

if(isPalin[i][j])

  cuts[i] = min{cuts[i], cuts[i + j] + 1}

参考:http://blog.csdn.net/ljphhj/article/details/22573983

 1 public class Solution {
 2     public int minCut(String s) {
 3         int min = 0;
 4         if(0 == s.length() || 1 == s.length())
 5             return min;
 6         boolean isPalin[][] = new boolean[s.length()][s.length()];
 7         int cuts[] = new int[s.length() + 1];
 8         int length = s.length();
 9         
10         //初始化cuts[]数组
11         for(int i = 0; i < length; i++)
12             cuts[i] = length - i;
13         //dp过程
14         for(int i = length - 1; i >= 0; i--){
15             for(int j = i; j < length; j++){
16                 if((s.charAt(i) == s.charAt(j) && (j - i < 2))
17                         || (s.charAt(i) == s.charAt(j) && isPalin[i + 1][j - 1])){
18                     isPalin[i][j] = true;
19                     cuts[i] = getMin(cuts[i], cuts[j + 1] + 1);
20                 }//if
21             }//for
22         }//for
23         
24         min = cuts[0];
25         
26         return min - 1;
27     }//minCut
28     
29     public int getMin(int num1, int num2){
30         return num1 < num2 ? num1 : num2;
31     }
32 }
原文地址:https://www.cnblogs.com/luckygxf/p/4271817.html