zoukankan      html  css  js  c++  java
  • 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.

     1 public class Solution {
     2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(triangle == null) return 0;
     6         if(triangle.size() == 0) return 0;
     7         int[] a = new int[triangle.size()];
     8         for(int i = 0; i < triangle.size(); i ++){
     9             a[i] = triangle.get(triangle.size() - 1).get(i);
    10         }
    11         for(int j = triangle.size() - 1; j > 0; j --){
    12             for(int i = 0; i < j; i ++){
    13                 a[i] = triangle.get(j - 1).get(i) + Math.min(a[i],a[i+1]);
    14             }
    15         }
    16         return a[0];
    17     }
    18 }

    第二遍:

     1 public class Solution {
     2     public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         Integer[] a = triangle.get(triangle.size()-1).toArray(new Integer[0]);
     6         for(int j = triangle.size() - 1; j > 0; j --)
     7             for(int i = 0; i < j; i ++)
     8                 a[i] = triangle.get(j-1).get(i) + Math.min(a[i],a[i+1]);
     9         return a[0];
    10     }
    11 }
  • 相关阅读:
    CentOS下设置ipmi
    CentOS 使用文件增加Swap空间
    CentOS LVM
    做IT需要掌握的电力基础知识
    CentOS 7搭建本地yum源
    Lsi卡和IB卡在CentOS中升级
    Mellanox 4036配置
    IdentityServer4入门二
    IdentityServer4入门一
    RAFT选举算法-分布式数据库困惑
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3336043.html
Copyright © 2011-2022 走看看