LeetCode——Palindrome Partitioning II
2014-05-22 23:03
239 查看
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.
思路:这道题的思路可以借鉴Palindrome Partitioning的思路,加以修改。
利用两处dp算法:
1、用来判断从i到j的子串是不是回文串
2、定义状态dp[i],表示字符串s的字串0到i,可以进行的最少分割。则最后dp[len-1]即为所要求的答案。
代码:
class Solution { public: vector<vector<int> > vt; bool dpjudge(string &s, int i, int j) { if (i > j) return false; if (vt[i][j] != -1) return vt[i][j]; if (i == j) return vt[i][j] = 1; if (s[i] != s[j]) return vt[i][j] = 0; else { if (i + 1 == j) return vt[i][j] = 1; else return vt[i][j] = dpjudge(s, i + 1, j - 1); } } int minCut(string s) { int len = s.length(); if (len < 2) return 0; vector<int> dp, tmp; dp.clear(), tmp.clear(), vt.clear(); //初始化dp和vt for (int i = 0; i < len; i++) { dp.push_back(0); tmp.push_back(-1); } for (int i = 0; i < len; i++) { vt.push_back(tmp); } for (int i = 1; i < len; i++) { if (dpjudge(s, 0, i)) { dp[i] = 0; continue; } int ans = i; for (int j = 0; j < i; j++) { if (dpjudge(s, j + 1, i)) ans = min(ans, dp[j] + 1); else ans = min(ans, dp[j] + i - j); } dp[i] = ans; } return dp[len - 1]; } };
相关文章推荐
- leetcode Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- [leetcode][DP] Palindrome Partitioning II
- [LeetCode]132 Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II
- Leetcode: Palindrome Partitioning II
- 147_leetcode_Palindrome Partitioning II
- 【Leetcode】Palindrome Partitioning II
- 【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
- leetcode Palindrome Partitioning II
- Palindrome Partitioning II Leetcode
- LeetCode Palindrome Partitioning II
- [leetcode刷题系列]Palindrome Partitioning II