classSolution {
public:int minDeletions(string s) {
returnhelper(s, 0, s.size() -1);
}
inthelper(const string& s, int i, int j) {
if (i >= j) return0;
if (s[i] == s[j]) return helper(s, i +1, j -1);
return1+ min(helper(s, i +1, j), helper(s, i, j -1));
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintminDeletions(String s) {
return helper(s, 0, s.length() - 1);
}
privateinthelper(String s, int i, int j) {
if (i >= j) return 0;
if (s.charAt(i) == s.charAt(j)) return helper(s, i + 1, j - 1);
return 1 + Math.min(helper(s, i + 1, j), helper(s, i, j - 1));
}
}
The top-down DP approach uses recursion with memoization to avoid recomputing results for the same substring. By storing results for each substring, we efficiently solve overlapping subproblems and reduce the exponential time complexity of the naive recursive solution.
We can use a DP table to store the minimum deletions needed for every substring. For each substring, if the boundary characters match, we use the result for the inner substring. Otherwise, we take the minimum deletions from either side plus one.
classSolution {
public:int minDeletions(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int len =2; len <= n; ++len) {
for (int i =0; i + len -1< n; ++i) {
int j = i + len -1;
if (s[i] == s[j]) {
dp[i][j] = dp[i +1][j -1];
} else {
dp[i][j] =1+ min(dp[i +1][j], dp[i][j -1]);
}
}
}
return dp[0][n -1];
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
publicintminDeletions(String s) {
int n = s.length();
int[][] dp =newint[n][n];
for (int len = 2; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if (s.charAt(i) == s.charAt(j)) {
dp[i][j]= dp[i + 1][j - 1];
} else {
dp[i][j]= 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defminDeletions(self, s: str) -> int:
n: int = len(s)
dp: list[list[int]] = [[0] * n for _ in range(n)]
for length in range(2, n +1):
for i in range(n - length +1):
j = i + length -1if s[i] == s[j]:
dp[i][j] = dp[i +1][j -1]
else:
dp[i][j] =1+ min(dp[i +1][j], dp[i][j -1])
return dp[0][n -1] if n >0else0