classSolution { public: intminCut(string s){ constint n = s.size(); // if s[i~j] is palindrome. vector<vector<bool>> valid(n, vector<bool>(n, true)); // dp[i] = min cuts of s[0~i]. vector<int> dp(n, n); for (int l = 2; l <= n; ++l) for (int left = 0, right = left + l - 1; right < n; ++left, ++right) valid[left][right] = s[left] == s[right] && valid[left + 1][right - 1]; for (int right = 0; right < n; ++right) { if (valid[0][right]) { dp[right] = 0; continue; } for (int left = 0; left < right; ++left) if (valid[left + 1][right]) dp[right] = min(dp[right], dp[left] + 1); } return dp[n - 1]; } };
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intminCut(string s){ constint n = s.size(); // dp[i] = min cuts of s[0~i]. vector<int> dp(n, n); for (int m = 0; m < n; ++m) // enumerate middle points. for (int d = 0; d <= 1; ++d) // odd and even length palindrome. for (int i = m, j = m + d; i >= 0 && j < n && s[i] == s[j]; --i, ++j) dp[j] = min(dp[j], (i ? (dp[i - 1] + 1) : 0)); return dp[n - 1]; } };