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
classSolution { int dp[101][101]; inthelper(vector<int>& A, int l, int r){ if(l >= r) return1; 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: intminimumMoves(vector<int>& arr){ memset(dp,-1,sizeof(dp)); returnhelper(arr,0,arr.size() - 1); } };