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:

  1. At each step of the game,the player can merge two adjacent piles to a new pile.
  2. The score is the number of stones in the new pile.

You are to determine the minimum of the total score.

Have you met this question in a real interview?

Yes

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

  1. 用循环实现,区间由小至大
public class Solution {
    /*
     * @param A: An integer array
     * @return: An integer
     */
    public int stoneGame(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return 0;
        }

        int[][] f = new int[A.length][A.length];
        int[][] sum = new int[A.length][A.length];

        for (int i = 0; i < sum.length; i++) {
            sum[i][i] = A[i];
            for (int j = i + 1; j < sum.length; j++) {
                sum[i][j] = sum[i][j - 1] + A[j];
            }
        }

        //initialization
        for (int i = 1; i < sum.length; i++) {
            f[i - 1][i] = sum[i - 1][i];
        }



        for (int l = 2; l < sum.length; l++) {
            for (int left = 0; left < sum.length - l; left++) {
                f[left][left + l] = Integer.MAX_VALUE;
                //enumerate k
                for (int k = left; k < left + l; k++) {
                    f[left][left + l] = Math.min(f[left][left + l], f[left][k] + f[k + 1][left + l] + sum[left][left + l]);   
                }
            }
        }
        return f[0][A.length - 1];
    }
}

results matching ""

    No results matching ""