DP : 132. Palindrome Partitioning II

痛定思痛。 2022-05-08 09:52 242阅读 0赞

132. 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.

Example:

Input: “aab”
Output: 1
Explanation: The palindrome partitioning [“aa”,“b”] could be produced using 1 cut.

  1. class Solution {
  2. public:
  3. int helper(vector<vector<int>>& dp,string& s,int x,int y) {
  4. int n = s.size();
  5. if(dp[x][y]>=0)
  6. return dp[x][y];
  7. if(x==y)
  8. dp[x][y] = 1;
  9. else if(y-x==1)
  10. dp[x][y] = s[x]==s[y];
  11. else if(s[x]==s[y])
  12. dp[x][y] = dp[x+1][y-1] >= 0 ? dp[x+1][y-1] : helper(dp,s,x+1,y-1);
  13. else dp[x][y] = 0;
  14. return dp[x][y];
  15. }
  16. int helper2(vector<vector<int>>& dp,vector<int>& dp2,int x) {
  17. int n = dp2.size();
  18. if(dp[x][n-1]) {
  19. dp2[x] = 0;
  20. return 0;
  21. }
  22. for(int j=x;j<n-1;++j) {
  23. if(dp[x][j])
  24. dp2[x] = min(dp2[x], (dp2[j+1] != INT_MAX ? dp2[j+1] : helper2(dp,dp2,j+1)) + 1);
  25. }
  26. return dp2[x];
  27. }
  28. int minCut(string s) {
  29. int n = s.size();
  30. if(n<=1) return 0;
  31. if(n==2) return !(s[0]==s[1]);
  32. vector<vector<int>> dp(n,vector<int>(n,-1));
  33. for(int i=0;i<n;++i) {
  34. for(int j=i;j<n;++j) {
  35. helper(dp,s,i,j);
  36. }
  37. }
  38. vector<int> dp2(n,INT_MAX);
  39. return helper2(dp,dp2,0);
  40. }
  41. };

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读