Triangle

来源:互联网 发布:急难先锋8016优化 编辑:程序博客网 时间:2024/06/05 08:15

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

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

这道题用dp就可以了, 从后往前扫避免需要另外的一个空间储存之前的dp数列


public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        // DP: in order to save space, just keep the previous line        int lvs = triangle.size();        if(lvs == 0)    return 0;                int prev = 0;        int[] dp = new int[lvs];        List<Integer> row = triangle.get(0);        dp[0] = row.get(0);                for(int i=1; i<lvs; i++){            row = triangle.get(i);            dp[i] = dp[i-1] + row.get(i);            for(int j= i-1; j>=0; j--){                int tmp = dp[j] + row.get(j);                if(j > 0)   tmp = Math.min(dp[j-1] + row.get(j), tmp);                dp[j] = tmp;            }                    }                int min = dp[0]; //err1: return the minimum of the dp array        for(int i=1; i<lvs; i++){            min = Math.min(min, dp[i]);        }        return min;    }}


0 0
原创粉丝点击