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


    思路:从下往上,每一行的结果根据下面一行的路基累计和而计算。(参考大神才晓得) 
    triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]) 
    对于此题子在面试的时候, 除了题意,还要要问清楚这些题的其他问题,比如 :传递的数据元素可以修改否? 最后求出的和sum会不会超出integer的范围? 

    
    
    package cn.edu.algorithm.huawei;

    import java.util.ArrayList;

    public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
    if (triangle == null || triangle.size() == 0) {
    return -1;
    }

    int len = triangle.size();
    int[][] dp = new int[len][len];

    for (int i = 0; i < len; i++) {
    dp[len - 1][i] = triangle.get(len - 1).get(i);
    }

    for (int i = len - 2; i >= 0; i--) {
    for (int j = 0; j <= i; j++) {
    dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + triangle.get(i).get(j);
    }
    }
    return dp[0][0];
    }

    public static void main(String[] args) {
    ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> list1 = new ArrayList();
    list1.add(1);

    ArrayList<Integer> list2 = new ArrayList();
    list2.add(2);
    list2.add(3);

    triangle.add(list1);
    triangle.add(list2);

    Solution s = new Solution();
    int path = s.minimumTotal(triangle);
    System.out.println(path);
    }
    }
     
  • 相关阅读:
    HDOJ 1556 线段树
    POJ 3977 折半枚举
    2017ACM省赛选拔赛题解
    关于四舍五入和截断
    POJ 3422 最小费用最大流
    Codeforces Round #407 (Div. 2) D. Weird journey 思维+欧拉
    POJ 3155 最大密度子图
    无向图最小割 stoer_wagner算法
    最大权闭合子图
    L2-001. 紧急救援 Dijkstra
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5829602.html
Copyright © 2011-2022 走看看