Leetcode_132. Palindrome Partitioning II_[DP]

Topic Link

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.

Meaning of the questions is equally simple and straightforward.

solution:

On the question Palindrome Partitioning , ideas can get a solution to this question, DFS exhaustive of all programs. However, only the DFS time out. This question requires only the number obtained by dividing a minimum number of methods. Under this issue, dfs (string & s, int idx) Returns s [idx, s.size () - 1] The minimum number of substrings divided times required. Can be found, there are a lot of double counting simplicity the DFS, since the s [0, idx) substring how many partitioning method, dfs (string & s, int idx) will be called many times, each time calculated dfs (string & s, int idx) returned result is the same. So, naturally think of memory search, which is dp.

class Solution {
public:
    vector<vector<bool>> is_palindrome;
    vector<int> dp;
    int minCut(string s) {
        int len = s.size();
        is_palindrome = std::move(vector<vector<bool>>(len, vector<bool>(len, false)));
        dp = std::move(vector<int>(len, len+1));
        for(size_t l=1; l<=len; l++)
            for(size_t head=0; head+l-1<len; head++){
                int tail = head+l-1;
                if(l == 1)
                    is_palindrome[head][tail] = true;
                else if(s[head]==s[tail] && (head == tail-1 || is_palindrome[head+1][tail-1]))
                    is_palindrome[head][tail] = true;
            }
        int ret = len;
        dfs(s, 0);
        return dp[0]-1;
    }

    int dfs(string& s, int hp){
        if(hp == s.size())
            return 0;
        if(dp[hp] < s.size()+1)
            return dp[hp];
        int ret = s.size()+1;
        for(size_t i=s.size()-hp; i>=1; i--)
            if(is_palindrome[hp][hp+i-1])
                ret = min(ret, 1+dfs(s, hp+i));
        return dp[hp] = ret;
    }
};

 

Guess you like

Origin www.cnblogs.com/jasonlixuetao/p/11973484.html