[LeetCode]—Palindrome Partitioning II 回文分割,求最小分割数
2014-08-13 14:38
513 查看
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
1since the palindrome partitioning
["aa","b"]could
be produced using 1 cut.
分析:在上一题的基础上需要计算最短切割数,采用动态规划分析。
直观上dp(i,j)表示区间[i , j] 之间的最小cut数,则有状态转移方程:
dp(i,j)=min{ dp(i , k)+dp(k+1, j) } 0<=i<=j<n , i<=k=<j
但是以上为2维动态规划,比较复杂,需要转换为1维表示。每次从i向右扫描,每找到一个回文算一个DP的话,就可以转换为区间[j , n-1] 之间最小的cut数了。则状态转移方程为:
f(i) = min {1+f( j+1 ) }
现在出现了新的问题,如何判断[ i , j ]之间是回文。如果每次从i到j 都比较一遍,太浪费了。这本身也就是一个动态规划问题。
定义状态p[i][j]=True的话,那么前提就是 str[i]==str[j] && ( j-i<2 || p[i+1][j-1] )
class Solution { public: int minCut(string s) { const int len=s.size(); int f[len+1]; bool p[len][len]; f[len]=-1; for(int i=len-1;i>=0;i--) f[i]=f[i+1]+1; for(int i=0;i<len;i++) for(int j=0;j<len;j++) p[i][j]=false; for(int i=len-1;i>=0;i--) for(int j=i;j<len;j++){ if(s[i]==s[j] && (j-i<2 || p[i+1][j-1])){ p[i][j]=true; f[i]=min(f[i],f[j+1]+1); } } } };
相关文章推荐
- 分割成回文需要的最小分割数 Palindrome Partitioning II @LeetCode
- 最小回文分割数 Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II-回文分割-DP优化
- [LeetCode 132] - 回文分割II(Palindrome Partitioning II)
- 动态规划——回文最小分割数(palindrome-partitioning-ii)
- 19. Palindrome Partitioning && Palindrome Partitioning II (回文分割)
- Palindrome Partitioning II(找给定字符串分割次数获取回文字串, 动态规划)
- LeetCode 132. Palindrome Partitioning II(回文切分)
- LeetCode 680. Valid Palindrome II (验证回文字符串 Ⅱ)
- Java for LeetCode 132 Palindrome Partitioning II
- LeetCode Palindrome Partitioning, Palindrome Partitioning II
- Leetcode 131&132. Palindrome Partitioning I & II
- Leetcode--Palindrome Partitioning II
- LeetCode: Palindrome Partitioning II
- 【LeetCode】Palindrome Partitioning I&II
- leetcode——Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- leetcode之 Palindrome Partitioning I&II
- leetcode — palindrome-partitioning-ii