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




和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];
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

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
讨论区还有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 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];
    }
};




你可能感兴趣的:(leetcode 132. Palindrome Partitioning II)