1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: int minCut(string s) { const int n = s.size(); vector<vector<bool>> valid(n, vector<bool>(n, true)); 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]; } };
|