1. 程式人生 > >[LeetCode] Palindrome Partitioning II 拆分迴文串之二

[LeetCode] 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 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

這道題是讓找到把原字串拆分成迴文串的最小切割數,需要用動態規劃Dynamic Programming來做,使用DP的核心是在於找出遞推公式,之前有道

地牢遊戲Dungeon Game的題也是需要用DP來做,而那道題是二維DP來解,這道題由於只是拆分一個字串,需要一個一維的遞推公式,我們還是從後往前推,遞推公式為:dp[i] = min(dp[i], 1+dp[j+1] )    i<=j <n,那麼還有個問題,是否對於i到j之間的子字串s[i][j]每次都判斷一下是否是迴文串,其實這個也可以用DP來簡化,其DP遞推公式為P[i][j] = s[i] == s[j] && P[i+1][j-1],其中P[i][j] = true if [i,j]為迴文。程式碼如下:

class Solution {
public
: int minCut(string s) { int len = s.size(); bool P[len][len]; int dp[len + 1]; for (int i = 0; i <= len; ++i) { dp[i] = len - i - 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 <= 1 || P[i + 1][j - 1])) { P[i][j] = true; dp[i] = min(dp[i], dp[j + 1] + 1); } } } return dp[0]; } };