[LeetCode] Palindrome Removal

1246. Palindrome Removal

Given an integer array arr, in one move you can select a palindromic subarray arr[i], arr[i+1], …, arr[j] where i <= j, and remove that subarray from the given array. Note that after removing a subarray, the elements on the left and on the right of that subarray move to fill the gap left by the removal.

Return the minimum number of moves needed to remove all numbers from the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
int dp[101][101];
int helper(vector<int>& A, int l, int r) {
if(l >= r) return 1;
if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = A[l] == A[r] ? helper(A,l+1,r-1) : INT_MAX;
for(int i = 0; i < r - l; i++) {
dp[l][r] = min(dp[l][r], helper(A,l,l+i) + helper(A,l+i+1,r));
}
return dp[l][r];
}
public:
int minimumMoves(vector<int>& arr) {
memset(dp,-1,sizeof(dp));
return helper(arr,0,arr.size() - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/05/PS/LeetCode/palindrome-removal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.