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 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.

    Solution:

     1 public class Solution {
     2     public int minimumTotal(List<List<Integer>> triangle) {
     3         if (triangle == null)
     4             return 0;
     5         int length = triangle.size();
     6         int dp[] = new int[length];
     7         for (int i = 0; i < length; ++i) {
     8             dp[i] = triangle.get(length - 1).get(i);
     9         }
    10         for (int j = length - 2; j >= 0; --j) {
    11             int[] temp = dp.clone();
    12             for (int i = j; i >= 0; --i) {
    13                 temp[i] = Math.min(dp[i], dp[i + 1]) + triangle.get(j).get(i);
    14             }
    15             dp = temp.clone();
    16         }
    17         return dp[0];
    18     }
    19 }

    rewrite:

     1 public class Solution {
     2     public int minimumTotal(List<List<Integer>> triangle) {
     3         if (triangle == null)
     4             return 0;
     5         int length = triangle.size();
     6         int dp[] = new int[length];
     7         for (int i = 0; i < length; ++i) {
     8             dp[i] = triangle.get(length - 1).get(i);
     9         }
    10         for (int j = length - 2; j >= 0; --j) {
    11             for (int i = 0; i <=j; ++i) {
    12                 dp[i] = Math.min(dp[i], dp[i + 1]) + triangle.get(j).get(i);
    13             }
    14         }
    15         return dp[0];
    16     }
    17 }

     前边儿的代码,在每一层上从后往前算,需要再开一个temp数组来放下一层的dp值;

    rewrite后的代码,直接在dp上进行操作,节省空间和时间。

  • 相关阅读:
    体检前注意事项
    SSO之CAS单点登录详细搭建教程
    如何通过session控制单点登录
    谈谈防止Ajax重复点击提交
    js判断是移动端还是pc端
    HttpClient通过GET和POST获取网页内容
    HttpClient 4.x 执行网站登录并抓取网页的代码
    360每日自动签到,领取积分 (java httpclient4.x)
    Java @override报错的解决方法
    无开发经验,初学python
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4059221.html
Copyright © 2011-2022 走看看