LeetCode:Palindrome Partitioning Ⅱ(DP)

Problem

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.

 

定义状态f[i] =区间[i,n-1]的最小cut数  p[i][j]表示是s[i]到s[j]是否为回文串

Solution

 1 class Solution {
 2 public:
 3     int minCut(string s) {
 4         
 5         //dp
 6         const int n=s.size();
 7         int f[n+1];
 8         bool p[n][n];
 9         fill_n(&p[0][0],n*n,false);
10         
11         //worst
12         for(int i=0;i<=n;i++)
13            f[i]=n-1-i;
14            
15         for(int i=n-1;i>=0;i--)
16             for(int j=i;j<n;j++)
17             if(s[i]==s[j]&&(j-i<2||p[i+1][j-1]))
18             {
19                 p[i][j]=true;
20                 f[i]=min(f[i],f[j+1]+1);
21             }
22             
23             return f[0];
24        
25 
26         
27     }
28 };

 

posted @ 2015-09-06 19:31  尾巴草  阅读(123)  评论(0编辑  收藏  举报