[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.
动态规划,dp[i]表示从s_0到s_i的最小cut,为了避免重复比较,定义标记矩阵flag[i][j],用来存储s_i到s_j是否为回文。
1 class Solution { 2 public: 3 int minCut(string s) { 4 vector<int> dp(s.length(), 0); 5 vector<vector<bool> > flag(s.length(), vector<bool>(s.length(), false)); 6 flag[0][0] = true; 7 for (int i = 1; i < s.length(); ++i) { 8 flag[i][i] = true; 9 dp[i] = dp[i-1] + 1; 10 for (int len = 1; len < i + 1; ++len) { 11 if (s[i-len] == s[i] && (len < 2 || flag[i-len+1][i-1])) { 12 dp[i] = (i - len == 0) ? 0 : min(dp[i], dp[i-len-1] + 1); 13 flag[i-len][i] = true; 14 } 15 } 16 } 17 return dp[s.length() - 1]; 18 } 19 };
换个字母代码更好理解一些。
1 class Solution { 2 public: 3 int minCut(string s) { 4 vector<int> dp(s.length(), 0); 5 vector<vector<bool> > flag(s.length(), vector<bool>(s.length(), false)); 6 flag[0][0] = true; 7 for (int j = 1; j < s.length(); ++j) { 8 flag[j][j] = true; 9 dp[j] = dp[j-1] + 1; 10 for (int i = 0; i < j; ++i) { 11 if (s[i] == s[j] && (i == j - 1 || flag[i+1][j-1])) { 12 dp[j] = (i == 0) ? 0 : min(dp[j], dp[i-1] + 1); 13 flag[i][j] = true; 14 } 15 } 16 } 17 return dp[s.length()-1]; 18 } 19 };
DFS版本超时了。
1 class Solution { 2 public: 3 bool isPail(string &s) { 4 int low = 0, high = s.length() - 1; 5 while (low < high) { 6 if (s[low] != s[high]) { 7 return false; 8 } 9 ++low; 10 --high; 11 } 12 return true; 13 } 14 15 void findNext(vector<vector<string> > &res, string &s, vector<string> part, int idx) { 16 if (idx == s.length()) { 17 res.push_back(part); 18 return; 19 } 20 string substr; 21 for (int len = s.length() - idx; len > 0; --len) { 22 substr = s.substr(idx, len); 23 if (isPail(substr)) { 24 part.push_back(substr); 25 findNext(res, s, part, idx + len); 26 part.pop_back(); 27 } 28 } 29 } 30 31 int minCut(string s) { 32 vector<vector<string> > res; 33 vector<string> part; 34 findNext(res, s, part, 0); 35 int min = INT_MAX; 36 for (int i = 0; i < res.size(); ++i) { 37 min = (min > res[i].size()) ? res[i].size() : min; 38 } 39 return min - 1; 40 } 41 };