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.

分析: 这道题目比较难,DP思路,假设D[n]为每个位置的minCut,从后往前开始统计, D[i] = D[j+1]+1, if s[i,j]为回文串,利用二维数组来记录s[i,j]是不是回文串

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

 

posted @ 2017-02-13 21:40  WillWu  阅读(99)  评论(0编辑  收藏  举报