题目描述:
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);
}
};
本文介绍了一种使用动态规划解决特殊打印机打印字符串问题的方法。该打印机每次只能打印相同的字符序列,并且可以从任意位置开始和结束打印,覆盖原有字符。通过递归地寻找最优解,实现最小打印次数。
1019

被折叠的 条评论
为什么被折叠?



