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 }
  • 相关阅读:
    Oracle 循环语句
    IDEA---SpringBoot同一个项目多端口启动
    Maven引入oracle驱动包
    Linux安装 PostgreSQL
    Oracle备份及备份策略
    Oracle优化的几个简单步骤
    Oracle RMAN备份策略
    常见的几种索引扫描类型
    插槽内容
    分布式系统session同步解决方案
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3336043.html
Copyright © 2011-2022 走看看