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.
和131. Palindrome Partitioning不同,普通DFS会超时,用记忆DFS剪枝后,能AC,但是用时还是太长。参考了讨论区,应该考虑用DP,状态方程为(dp[i][j]代表字符串中坐标i到坐标j是否是回形子串,count[i]为坐标i之前子串的最小分割子串数),到某一下标时的最小分割子串,由根据它所有包含它最后一个字符的分割子串s.substring[j,i+1],得到的前一个下标时的的最小子串数count[j-1]+1。得到它们的最小值。count[i]借助dp[i][j]判断回形字符串
dp[i][j]=dp[i+1][j-1]&&s[i]==s[j];
dp[i][j]=dp[i+1][j-1]&&s[i]==s[j];
if(dp[i+1][j-1]&&s[i]==s[j]) {
count[i]=min(count[j-1]+1);
}else{
count[i]=i;
}
记忆化dfs:
//记忆化dfs,记录每个节点(字符)之后字符串中的最小数,后面搜到就不用继续重新搜了 public int minCut(String s) { int[] mem=new int[s.length()]; dfs(s,mem,0); return mem[0]-1;//区间要-1 } public int dfs(String s,int[] mem,int index){ if(s.equals("")){ return 0; } if(mem[index]!=0){ return mem[index]; } int count=Integer.MAX_VALUE; for(int i=0;i<s.length();i++){//自身已经分了一次 if(check(s.substring(0,i+1))){ count=Math.min(count,dfs(s.substring(i+1),mem,index+i+1));//count表示子串最小个数 } } mem[index]=count+1; return count+1;//因为本次已经划分了一次子串 } public boolean check(String str){ for(int i=0;i<str.length()/2;i++){ if(str.charAt(i)!=str.charAt(str.length()-1-i)){ return false; } } return true; }
dp解法,维护2个dp数组:
public int minCut(String s) {//dp[i][j]=dp[i+1][j-1]&&s[i]==s[j] boolean[][] dp=new boolean[s.length()][s.length()]; int[] count=new int[s.length()]; dp[0][0]=true; for(int i=0;i<s.length();i++){ int min=i; for(int j=0;j<=i;j++){ if(s.charAt(i)==s.charAt(j)&&(i-1<j+1||dp[i-1][j+1])){ dp[i][j]=true; min=j==0?0:Math.min(min,count[j-1]+1); } } count[i]=min; } return count[count.length-1]; }讨论区还有O(n)space的方案,非常巧妙https://leetcode.com/problems/palindrome-partitioning-ii/discuss/42198/My-solution-does-not-need-a-table-for-palindrome-is-it-right-It-uses-only-O(n)-space.?page=4基本思想是某一位cut[i+j+1],由前面cut[i-j]得到,其中s[i-j,i+j]子串是回形字符串。这里的循环很巧妙,如果s[i-j]==s[i+j]是j就继续增大j,扩大范围。因为太巧妙,所以转过来,cut[k] is correct for every k <= i。
//转自leetcode讨论区大神tqlong,https://leetcode.com/problems/palindrome-partitioning-ii/discuss/42198/My-solution-does-not-need-a-table-for-palindrome-is-it-right-It-uses-only-O(n)-space.?page=4 class Solution { public: int minCut(string s) { int n = s.size(); vector<int> cut(n+1, 0); // number of cuts for the first k characters for (int i = 0; i <= n; i++) cut[i] = i-1; for (int i = 0; i < n; i++) { for (int j = 0; i-j >= 0 && i+j < n && s[i-j]==s[i+j] ; j++) // odd length palindrome cut[i+j+1] = min(cut[i+j+1],1+cut[i-j]); for (int j = 1; i-j+1 >= 0 && i+j < n && s[i-j+1] == s[i+j]; j++) // even length palindrome cut[i+j+1] = min(cut[i+j+1],1+cut[i-j+1]); } return cut[n]; } };