leetcode 120.Triangle | Java最短代码实现

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

【抛砖】

考察动态规划,这里从底层开始,逐层往上层动态求和,最后得到的最小和就是dp[0]:

    public int minimumTotal(List<List<Integer>> triangle) {
        int[] dp = new int[triangle.size() + 1];
        for (int i = triangle.size() - 1; i >= 0; i--)
            for (int j = 0; j < triangle.get(i).size(); j++)
                dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
        return dp[0];
    }

43 / 43 test cases passed. Runtime: 6 ms  Your runtime beats 40.91% of javasubmissions.

【补充】

同样的动归,采用深度优先,很容易想到用递归法,但是这种方法在数据量很大时超时了:

    public int minimumTotal(List<List<Integer>> triangle) {
        return findMinPath(triangle, 0, Integer.MAX_VALUE, 0, 0);
    }
    public int findMinPath(List<List<Integer>> triangle, int curSum, int min, int index, int level) {
        curSum += triangle.get(level).get(index);
        if (level == triangle.size() - 1)
            return Math.min(min, curSum);
        return Math.min(findMinPath(triangle, curSum, min, index, level + 1),
                findMinPath(triangle, curSum, min, index + 1, level + 1));
    }

欢迎优化!

你可能感兴趣的:(java,LeetCode,array,dynamic,programming)