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.

直观思想,在I的基础上改进,不过怎么都过不了,超时,即使用了DP求回文,加上剪枝。

class Solution {
public:
    int minCut(string s) {
        if (s.empty()) return 0;
        
        int cuts = -1;
        int size = s.size();
        int mincuts = size - 1;
        vector<vector<bool>> dp(size, vector<bool>(size, false));
        for (int i = size - 1; i >= 0; --i) {
           for (int j = i; j < size; ++j) {
               if (s[i] == s[j] && (j - i < 2 || dp[i+1][j-1])) {
                   dp[i][j] = true;
               }
           }
        }
        
        partitionUtil(dp, s, 0, size - 1, cuts, mincuts);
        
        return mincuts;
    }
    
    void partitionUtil(vector<vector<bool>> &dp, string &s, int start, int end, int cuts, int &mincuts) {
        if (start > end) {
            if (cuts < mincuts) {
                mincuts = cuts;
            }
        }
        else {
            for (int i = start; i <= end; ++i) {
                if (dp[start][i] && cuts < mincuts) {
                    partitionUtil(dp, s, i+1, end, cuts + 1, mincuts);
                }
            }
        }
    }
};
网上搜索,原来呀求最小cut仍然可以用DP,综合起来代码很简洁。DFS耗费时间太多了。

class Solution {
public:
    int minCut(string s) {
        if (s.empty()) return 0;
        
        int size = s.size();
        vector<int> cuts(size+1, 0);
        vector<vector<bool>> dp(size, vector<bool>(size, false));
        for (int i = size - 1; i >= 0; --i) {
            cuts[i] = size - i;
            for (int j = i; j < size; ++j) {
                if (s[i] == s[j] && (j - i < 2 || dp[i+1][j-1])) {
                    dp[i][j] = true;
                    cuts[i] = min(cuts[i], 1 + cuts[j+1]);
                }
            }
        }
        
        return (cuts[0] - 1);
    }
};
给力的两篇分析,学习了。

http://blog.csdn.net/yutianzuijin/article/details/16850031
http://blog.csdn.net/u011095253/article/details/9177451

=====================第二次====================

class Solution {
public:
    int minCut(string s) {
        int size = s.size();
        vector<int> cuts(size+1, 0);
        vector<vector<bool>> palindromes(size, vector<bool>(size, false));
        for (int i = size - 1; i >= 0; --i) {
            cuts[i] = size - i;
            for (int j = i; j < size; ++j) {
                if (s[i] == s[j] && (j - i < 2 || palindromes[i+1][j-1])) {
                    palindromes[i][j] = true;
                    cuts[i] = min(cuts[i], cuts[j+1] + 1);
                }
            }
        }
        
        return cuts[0] > 0 ? cuts[0] - 1 : 0;
    }
};


你可能感兴趣的:(LeetCode,dp)