n^2的预处理求出那些子串是回文的,哪些不是, 然后再n^2的dp。
const int MAXN = 2500;
int n;
bool is[MAXN][MAXN];
int dp[MAXN];
class Solution {
public:
int minCut(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
n = s.size();
for(int i = 0; i < n; ++ i)
is[i][i] = true;
for(int i = 1; i < n; ++ i)
is[i - 1][i] = s[i - 1] == s[i];
for(int len = 3; len <= n; ++ len)
for(int st = 0; st + len - 1 < n; ++ st){
int en = st + len - 1;
if(s[st] != s[en])
is[st][en] = false;
else
is[st][en] = is[st + 1][en - 1];
}
dp[0] = 0;
for(int i = 1; i < n; ++ i)
if(is[0][i])
dp[i] = 0;
else{
int in = n;
for(int j = i; j >= 1; -- j)
if(is[j][i])
in = min(in, dp[j - 1]);
dp[i] = in + 1;
}
return dp[n - 1];
}
};