I submitted both approaches. Using LPS, I get wrong answer but direct approach worls. I’m not able to figure out a test cases where they both would be different. Any ideas?
both approaches have 2D DP. dp[i][j]
LPS:
vector<vector> dp(n, vector (n, 0));
for(int i=0;i<n;i++) dp[i][i] = 1;
for(int i=1;i<n;i++) {
dp[i-1][i] = str[i - 1] == str[i] ? 2 : 0;
for(int j=i-2;j>=0;j--) {
if (str[j] == str[i]) dp[j][i] = dp[j+1][i-1] + 2;
else dp[j][i] = max(dp[j+1][i], dp[j][i-1]);
}
}
return n - dp[0][n-1];
Direct Approach:
int n = str.size();
vector<vector<int>> dp(n, vector<int> (n, 0));
for(int i=1;i<n;i++) {
dp[i-1][i] = str[i - 1] == str[i] ? 0 : 1;
for(int j=i-2;j>=0;j--) {
if (str[j] == str[i]) dp[j][i] = dp[j+1][i-1];
else dp[j][i] = 1 + min(dp[j+1][i], dp[j][i-1]);
}
}
return dp[0][n-1];
created
last reply
- 1
reply
- 19
views
- 2
users