Stone Game
There is a stone game.At the beginning of the game the player picksnpiles of stones in a line.
The goal is to merge the stones in one pile observing the following rules:
- At each step of the game,the player can merge two adjacent piles to a new pile.
- The score is the number of stones in the new pile.
You are to determine the minimum of the total score.
Example
For[4, 1, 1, 4], in the best solution, the total score is18:
1. Merge second and third piles =
>
[4, 2, 4], score +2
2. Merge the first two piles =
>
[6, 4],score +6
3. Merge the last two piles =
>
[10], score +10
Other two examples:[1, 1, 1, 1]return8[4, 4, 5, 9]return43
public int stoneGame(int[] A) {
if(A == null || A.length == 0) {
return 0;
}
int n = A.length;
int[][] dp = new int[n][n];
int[][] sum = new int[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];
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
for(int i = 0; i < n; i++) {
dp[i][i] = 0;
}
return search(A, 0, n - 1, dp, sum);
}
public int search(int[] A, int start, int end, int[][] dp, int[][] sum) {
if(dp[start][end] != Integer.MAX_VALUE) {
return dp[start][end];
}
if(start == end) {
return dp[start][end];
}
int value = Integer.MAX_VALUE;
for(int i = start; i < end; i++) {
value = Math.min(value, search(A, start, i, dp, sum) + search(A, i + 1, end, dp, sum) + sum[start][end]);
}
dp[start][end] = value;
return dp[start][end];
}