• 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     }
  • 相关阅读:
    黑白棋_lduoj_dfs深搜
    lduoj_2021年初寒假训练第41场
    Git学习day02
    Git学习day01
    python学习之urllib的使用
    SQL语句之授权与收回
    PHP学习之有问题找谁
    PHP学习之没有权限修改hosts文件
    PHP学习之创建本地站点
    python学习之常见错误
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677342.html
Copyright © 2020-2023  润新知