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 }
  • 相关阅读:
    观察者模式 java实现
    Decorator 模式
    Adapter 模式 java 实现
    Singleton 模式 Java,c++实现
    抽象工厂 java实现
    工厂方法模式 java实现
    简单工厂模式 Java实现
    【4】学习JS 数据结构与算法笔记
    【3】JavaScript编程全解笔记(三)
    【3】如何高效学习笔记
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3336043.html
Copyright © 2011-2022 走看看