Approach
We can use a dp
matrix, where element dp[i][j]
represents the minimum turn to print substring s[i...j]
.
Then, there are two cases:
- case 1: We print
s[i]
separately, now we havedp[i][j] = 1 + dp[i + 1][j]
. - case 2: There is a char
s[k] == s[i]
, then the strings[i...k]
can be obtained by printing some new substrings on the ranges[i...k]
, now we havedp[i][j] = dp[i][k-1]+dp[k+1][j]
Combining case 1 and case 2, we can now write the update formula for dynamic programming:
|
|
the base case is when i > j
, d[pi][j] = 0
and when i=j
, dp[i][j] = 1
.
Complexity
Time complexity: iterate the matrix once, each iteration takes $O(n)$ time. $$O(n^3)$$
Space complexity: use a
dp
matrix of size $n\times n$ to store the result $$O(n^2)$$
Code
|
|