题目描述:
There is a strange printer with the following two special requirements:
The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.
Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.
分析:
这是一道动态规划的题目,用一个二维数组来储存状态,dp[i][j]表示,从i到j的最小turn,显然有状态转移方程,j>p>i,if s[p]==s[j],dp[i][j]=min(dp[i][j],dp[i][p]+dp[p+1][j-1]).
代码如下:
int dp[100][100];
string s;
int dfs( int l, int r)
{
if (l > r) return 0;
if (dp[l][r]) return dp[l][r];
dp[l][r] = dfs( l, r - 1) + 1;
for (int i = l; i < r; ++i)
{
if (s[i] == s[r])
{
dp[l][r] = min(dp[l][r], dfs(l, i) + dfs( i + 1, r - 1));
}
}
return dp[l][r];
}
int strangePrinter(string s1)
{
s=s1;
return dfs( 0, s.size() - 1);
}
};