Triangle

来源:互联网 发布:淘宝改差评先打钱 编辑:程序博客网 时间:2024/06/06 08:38

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.

思路:
这里写图片描述
这里写图片描述

public class Solution {    public int minimumTotal(List<List<Integer>> triangle) {        int m=triangle.size();        if(triangle.get(m-1).size()==0) return 0;        if(m==0) return 0;        int[] nums=new int[m];        for(int i=0;i<m;i++)         nums[i]=triangle.get(m-1).get(i);        for(int i=m-2;i>=0;i--)        {            List<Integer> temp=triangle.get(i);              for(int j=0;j<temp.size();j++)              {                  int min = nums[j] < nums[j+1] ? nums[j] : nums[j+1] ;                  nums[j]=temp.get(j)+min;              }        }        return nums[0];    }}
0 0
原创粉丝点击