標籤:leetcode 演算法 面試
【題目】
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.
【題意】
給定一個字串s, 返回最小切割次數,是的所有的切割子串都為迴文。
【思路】
DP,依次確定s[1...n]的最小分割次數
假設用minCuts[i]表示,以第i結尾的字串的最小切分次數。
那麼怎麼確定minCuts[i]. 我們已知了minCuts[j] j=0,1,...,i-1
對於i之前的每個位置j, 如果s[j+1,..,i]為迴文串,則j為切割點的最小切割次數就是minCuts[j]+1;
所以我們要從所有的j中取一個位置使得i位置的切割次數最小的位置作為切割點,即minCuts[i]=min{minCuts[j]+1} s[j+1,..,i]是迴文,j=0,1...i-1
【代碼】
class Solution {public: int minCut(string s) { int len=s.length(); if(len==0||len==1)return 0; //構造迴文判別矩陣 vector<vector<bool> > isPal(len, vector<bool>(len, false)); //初始化isPal[i][i] for(int i=0; i<len; i++) isPal[i][i]=true; //初始化isPal[i][i+1] for(int i=0; i<len-1; i++) if(s[i]==s[i+1])isPal[i][i+1]=true; //初始化其他i<j的子串 for(int i=len-3; i>=0; i--) for(int j=i+2; j<len; j++) isPal[i][j]=(s[i]==s[j])&&isPal[i+1][j-1]; //求最小切割 vector<int> minCuts(len, 0); //記錄以i結尾的子串的最小切分數 for(int i=0; i<len; i++){ int mincut=INT_MAX; for(int j=-1; j<i; j++){ if(isPal[j+1][i]){ if(j==-1)mincut=0; else if(minCuts[j]+1<mincut)mincut=minCuts[j]+1; } } if(mincut!=INT_MAX)minCuts[i]=mincut; } return minCuts[len-1]; }};