[LeetCode] Palindrome Partitioning II [12]
来源:互联网 发布:学编程用什么笔记本 编辑:程序博客网 时间:2024/06/05 19:40
题目
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.
原题链接
解题思路
给一个字符串,如果字符串可以划分成若干子回文字符串,返回最小的划分数量。
这个题如果还用之前求所有划分组合的循环加递归方法的话,就会得到超时的错误。这是就要考虑别的方法,动态规划倒是一个不错的方法,但是动态规划最重要的是要找到动态方程。
本题的动态方程:
dp[i] = min(dp[i], dp[j+1]+1)), i<=j<n;
dp[i] : 表示从 i 到串尾的最小划分数。
代码实现
下面代码中imap[i][j]==1表示str[i]==str[j]并且从 i 到 j 的字符串是个回文。
class Solution {public: int minCut(string s) { int n = s.size(); vector<int> dp(n+1, 0); vector<vector<int> > imap(n+1, vector<int>(n+1, 0)); for(int i=n-1;i>=0; --i){ dp[i] = n-i; for(int j=i; j<n; ++j){ if(s[i] != s[j]) continue; if(j-i<2 || imap[i+1][j-1]==1){ imap[i][j] = 1; dp[i] = min(dp[i], dp[j+1] +1); } } } return dp[0]-1; }};
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28904745 )
5 0
- [LeetCode] Palindrome Partitioning II [12]
- LeetCode : 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
- [leetcode]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
- LeetCode Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- 处理驾校学员系统编号重复的问题
- 矩阵原地转置
- Test
- 补充个python监控小函数,证书过期发送警告
- 如何修改myeclipse中web项目的工作路径或默认路径
- [LeetCode] Palindrome Partitioning II [12]
- lynxos
- 再访俄罗斯地下世界
- 修改CMD命令回显语言 中文->English
- Tomcat8 安装和运行
- C罗挑战金球奖魔咒! 世界杯避重走小罗旧路
- JAVA中的集合类
- 整数划分
- Responder Chain简析