在C ++中重复删除回文子字符串后删除字符串的最少步骤
问题陈述
给定一个仅包含整数字符的字符串。我们需要以最少的步骤删除此字符串的所有字符,而在一步中,我们可以删除作为回文的子字符串。删除子字符串后,其余部分将串联在一起。
示例
如果输入字符串为3441213,则至少需要2个步骤
首先从字符串中删除121。现在剩下的字符串是3443
删除剩下的字符串,因为它是回文
算法
我们可以使用动态编程来解决这个问题
1. Let dp[i][j] denotes the number of steps it takes to delete the substring s[i, j]2. Each character will be deleted alone or as part of some substring so in the first case we will delete the character itself and call subproblem (i+1, j)
3. In the second case we will iterate over all occurrence of the current character in right side, if K is the index of one such occurrence then the problem will reduce to two subproblems (i+1, K – 1) and (K+1, j)
4. We can reach to this subproblem (i+1, K-1) because we can just delete the same character and call for mid substring
5. We need to take care of a case when first two characters are same in that case we can directly reduce to the subproblem (i+2, j)
示例
#include <bits/stdc++.h>using namespace std;
int getMinRequiredSteps(string str) {
int n = str.length();
int dp[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
dp[i][j] = 0;
}
}
for (int len = 1; len <= n; len++) {
for (int i = 0, j = len - 1; j < n; i++, j++) {
if (len == 1)
dp[i][j] = 1;
else {
dp[i][j] = 1 + dp[i + 1][j];
if (str[i] == str[i + 1]) {
dp[i][j] = min(1 + dp[i+ 2][j], dp[i][j]);
}
for (int K = i + 2; K <= j; K++){
if (str[i] == str[K]) {
dp[i][j] =
min(dp[i+1][K-1] + dp[K+1][j], dp[i][j]);
}
}
}
}
}
return dp[0][n - 1];
}
int main() {
string str = "3441213";
cout << "Minimum required steps: " <<
getMinRequiredSteps(str) << endl;
return 0;
}
当您编译并执行上述程序时。它产生以下输出
输出结果
Minimum required steps: 2
以上是 在C ++中重复删除回文子字符串后删除字符串的最少步骤 的全部内容, 来源链接: utcz.com/z/322176.html