LeetCode: Palindrome Partitioning II
来源:互联网 发布:适合冬天的沐浴露 知乎 编辑:程序博客网 时间:2024/06/06 22:49
思路:这个题目不能用深度搜索来进行求解,会超时,参考了网上讨论的DP算法,用一个ret[i] 表示 从i到字符末尾需要切断的次数,则 ret[i] = min(ret[i], ret[j] + 1), j = i+1, ...,n。ret[i]都初始化为 n - i -1 表示切成单个字符需要的次数。为了不重复计算i 到 j是否为回文字符串,可以用一个标记数组dp[i][j]来进行表示子串s(i,...j)是否为回文串,如果s[i] = s[j] ,则dp[i][j] = dp = [i+1][j-1], i+1 < j-1,否则dp[i][j] = true。
code:
class Solution {public: int minCut(string s) { int len = s.length(); int * ret = new int[len]; vector<bool> temp(len,false); vector<vector<bool> > dp(len,temp); for(int i = 0;i < len;i++) ret[i] = len - i - 1; for(int i = len-1;i >= 0;i--){ for(int j = i;j < len;j++){ if(s[i] == s[j]){ if(i+1 <= j-1) dp[i][j] = dp[i+1][j-1]; else dp[i][j] = true; if(dp[i][j]){ if(j < len-1) ret[i] = ret[i] < ret[j+1] + 1 ? ret[i] : ret[j+1] + 1; else ret[i] = 0; } } } } return ret[0]; }};
0 0
- 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
- [LeetCode] Palindrome Partitioning II
- hibernate一级缓存和二级缓存的区别与联系
- HDU_2041 超级楼梯
- linux c ---关于EOF
- sql数据库中统计表的个数
- Unity3D编辑器插件编写
- LeetCode: Palindrome Partitioning II
- BestCoder #2 1001 TIANKENG’s restaurant && Nyoj 168 房间安排
- wiki 1304 拓扑序记数
- 欢迎smilevvaa在ChinaUnix博客安家!
- 宗遵卓族柞住锥
- 将博客搬至CSDN
- 20年的烟龄戒不掉
- 凯里市一游
- 恢复Iphone手机的数据