[LeetCode] Triangle

来源:互联网 发布:les的交友软件 编辑:程序博客网 时间:2024/06/04 00:29

Total Accepted: 8954 Total Submissions: 33737

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).

// compute shortest path in topological orderpublic class Solution {    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {        int[] dp = new int[triangle.size()];                for (int i = 0; i < triangle.size(); i++) {            if (i == 0) {                dp[0] = triangle.get(0).get(0);                continue;            }                        // backward            for (int j = i; j >= 0; j--) {                int val1 = Integer.MAX_VALUE;                int val2 = Integer.MAX_VALUE;                                if (j != 0)     val1 = dp[j-1];                if (j != i)     val2 = dp[j];                                dp[j] = triangle.get(i).get(j).intValue() + (val1 < val2 ? val1 : val2);                     }        }                int min = Integer.MAX_VALUE;                for (int i = 0; i < triangle.size(); i++) {            if (dp[i] < min) min = dp[i];        }                return min;    }}

0 0
原创粉丝点击