i ~ [start, end - 1], => [start, i], [i + 1, end - 1]
for(int i = start; i < end; i++){int cost =memoizedSearch(start, i, A, dp, sum)+memoizedSearch(i +1, end, A, dp, sum)+ sum[end +1] - sum[start]; min =Math.min(min, cost);}
i ~ [start + 1, ... end], => [start, i - 1], [i, end]
for(int i = start +1; i <= end; i++){int cost =memoizedSearch(start, i -1, A, dp, sum)+memoizedSearch(i, end, A, dp, sum)+ sum[end +1] - sum[start]; min =Math.min(min, cost);}
Solution
DP - (252 ms)
publicclassSolution { /** * @param A an integer array * @return an integer */intsearch(int l,int r,int[][] f,int[][] visit,int[][] sum) {if(visit[l][r] ==1) {return f[l][r]; }if(l == r) { visit[l][r] =1;return f[l][r]; } f[l][r] =Integer.MAX_VALUE;for (int k = l; k < r; k++) { f[l][r] =Math.min(f[l][r],search(l, k, f, visit, sum)+search(k +1, r, f, visit, sum)+ sum[l][r]); } visit[l][r] =1;return f[l][r]; }publicintstoneGame(int[] A) {if (A ==null||A.length==0) {return0; }int n =A.length;// initializeint[][] f =newint[n][n];int[][] visit =newint[n][n];for (int i =0; i < n; i++) { f[i][i] =0; }// preparationint[][] sum =newint[n][n];for (int i =0; i < n; i++) { sum[i][i] =A[i];for (int j = i +1; j < n; j++) { sum[i][j] = sum[i][j -1] +A[j]; } }returnsearch(0, n-1, f, visit, sum); }}
(Preferred) Divide and Conquer + Memoization (251 ms AC)
publicclassSolution { /** * @param A an integer array * @return an integer */publicintstoneGame(int[] A) {// Write your code hereif(A ==null||A.length==0) return0;int n =A.length;// Minimum cost to merge interval dp[i][j]int[][] dp =newint[n][n];int[] sum =newint[n +1];// Pre-process interval sumfor(int i =0; i < n; i++){ sum[i +1] = sum[i] +A[i]; }returnmemoizedSearch(0, n -1, A, dp, sum); }privateintmemoizedSearch(int start,int end,int[] A,int[][] dp,int[] sum){if(start > end) return0;if(start == end) return0;if(start +1== end) returnA[start] +A[end];if(dp[start][end] !=0) return dp[start][end];int min =Integer.MAX_VALUE;for(int i = start; i < end; i++){int cost =memoizedSearch(start, i, A, dp, sum)+memoizedSearch(i +1, end, A, dp, sum)+ sum[end +1] - sum[start]; min =Math.min(min, cost); } dp[start][end] = min;return min; }}