leetcode: Palindrome Partitioning II
2014-05-21 20:23
232 查看
这题在Palindrome Partitioning的基础上还需要一次动态规划。
dp[i][j]保存i到j是否是回文
dp2[i]保存从0到i需要的最小cut数
状态转换方程:dp[i] = min(dp[j])+1 ( 0=< j < i)
dp[i][j]保存i到j是否是回文
dp2[i]保存从0到i需要的最小cut数
状态转换方程:dp[i] = min(dp[j])+1 ( 0=< j < i)
class Solution { public: int minCut(string s) { if( s.size() <= 1) return 0; int size = s.size(); vector< vector< bool> > dp( size, vector< bool>( size, false)); for( int i = 0; i < size; ++i) dp[i][i] = true; for( int i = 0; i < size; ++i){ for( int j = 0; j < i; ++j){ if( s[j] == s[i] && dp[j+1][i-1]){ dp[j][i] = true; } if( s[j] == s[i] && j == i - 1){ dp[j][i] = true; } } } vector< int> dp2(size, 0); int tmp = 0; for( int i = 0; i < size; ++i){ if(dp[0][i]){ dp2[i] = 0; continue; } tmp = 0x7fffffff; for( int j = 0; j < i; ++j){ if(dp[j+1][i]){ if(tmp > dp2[j]+1){ tmp = dp2[j] + 1; } } dp2[i] = tmp; } } return dp2[size-1]; } };
相关文章推荐
- 【Leetcode】Palindrome Partitioning II
- leetcode第19题(palindrome-partitioning-ii)
- [leetcode] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II 解题笔记
- leetcode Palindrome Partitioning II
- Leetcode--Palindrome Partitioning II
- Leetcode Palindrome Partitioning II
- leetcode -- Palindrome Partitioning II -- 重点
- Palindrome Partitioning II Leetcode Python
- [leetcode][DP] Palindrome Partitioning II
- LeetCode : Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- Leetcode Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- leetcode之 Palindrome Partitioning I&II
- Leetcode: Palindrome Partitioning I & II
- LeetCode132 Palindrome Partitioning II
- LeetCode 20 Palindrome Partitioning II