Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 132. Palindrome Partitioning II

Rain Hu

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 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. DP

vector<vector<bool>> dp;
void init(string& s) {
    for (int i = 0; i < s.length(); i++) {
        isPalindrome(s, i, i);      // 奇數型
        isPalindrome(s, i, i+1);    // 偶數型
    }
}

int minCut(string& s) {
    int n = s.length();
    dp = vector<vector<bool>>(n, vector<bool>(n, false));
    init(s);   // 將回文先用 memo[left][right] 的方式存起來 
    
    vector<int> cnt(n+1, n-1);      // dp
    cnt[0] = -1;                    // 若問題問可拆為多少組,cnt[0]定為 0,若問需切幾刀,cnt[0]定為 -1
    for (int j = 0; j < n; j++) {
        for (int i = 0; i <= j; i++) {
            if (dp[i][j]) {
                cnt[j+1] = min(cnt[j+1], cnt[i]+1);
            }
        }
    }
    
    return cnt[n];
}
void isPalindrome(string& s, int i, int j) {
    while (i >= 0 && j < s.length()) {
        if (s[i] != s[j]) break;
        dp[i][j] = true;
        i--; 
        j++;
    }
}

回目錄 Catalog


Share this post on:

Previous
[Algo] 3-1. Two Pointer/Sliding Window
Next
[Algo] 3-0. Sorting