zoukankan      html  css  js  c++  java
  • 120. Triangle

    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.

    给定一个三角形,找出从顶到底的最小路径和,每一步可以从上一行移动到下一行相邻的数字 

    思路:由底向上依次获取到第i层的最小值。最终顶层节点值就是最小路径和

     1     public int minimumTotal(List<List<Integer>> triangle) {
     2         if(triangle.size() == 0) return -1;
     3         if(triangle.size() == 1) return triangle.get(0).get(0);
     4         for(int i=triangle.size()-2;i>=0;i--){
     5             for(int j=0;j<=i;j++){
     6                int minValue =  Math.min(triangle.get(i+1).get(j),triangle.get(i+1).get(j+1)) + triangle.get(i).get(j);
     7                triangle.get(i).set(j,minValue);
     8             }
     9         }
    10         return triangle.get(0).get(0);     
    11     }
  • 相关阅读:
    jQuery-1.样式篇---属性与样式
    jQuery-1.样式篇---选择器
    jQuery-1.样式篇
    随机数
    UIButton
    UILabel
    webView
    气泡聊天
    下拉和上拉刷新
    LimitDemo
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677342.html
Copyright © 2011-2022 走看看