[leetcode] Palindrome Partitioning II

Palindrome Partitioning II Mar 1

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

思路很容易,就是2个2D的DP问题,for循环的写法需要思考一下啦,还有初始化的时候注意一下

class Solution {
public:
    int minCut(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int N = s.size();
        vector<vector<bool> > isPalin(N, vector<bool>(N, 1));
        
        for(int i = N - 1; i >= 0; i--){
            for(int j = i+1; j < N; j++ ){
                
                if(i+1 >= N || j-1 < 0) continue;
                isPalin[i][j] =(isPalin[i+1][j-1] && s[i] == s[j]);
            }
        }
        
        vector<int> f(N, 1);
        
        int tmp;
        for(int i = 0; i < N; i++){
            if(isPalin[0][i]){
               f[i] = 0;
               continue;
            }else{
                tmp = i;
            }
        
            for(int j = 0; j < i; j++){
                if(isPalin[j+1][i]){
                    tmp = min(tmp, f[j]+1);
                }
            }
            f[i] = tmp;
        }
        
        return f[N-1];
    }
};


你可能感兴趣的:(LeetCode)