【Leetcode】120.三角形最小路径和

栏目: 编程工具 · 发布时间: 6年前

内容简介:给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。例如,给定三角形:自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。

题目

给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。

例如,给定三角形:

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。

说明:

如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。

题解

这道题目和之前A过的杨辉三角差不多,一看就是动态规划。

动态规划最主要的是确定状态表达式。而要求在o(n)的空间复杂度来解决这个问题,最主要的是要想清楚,更新状态的时候,不破坏下一次计算需要用到的状态。

我们采用"bottom-up"的动态规划方法来解本题。

状态表达式为:

dp[j] = min(dp[j], dp[j+1]) + triangle[j];

【Leetcode】120.三角形最小路径和

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int row = triangle.size();
        List<Integer> res = new LinkedList<>(triangle.get(row - 1));
        for (int i = row - 2; i >= 0; i--) {
            List<Integer> currentRow = triangle.get(i);
            for (int j = 0; j < currentRow.size(); j++) {
                res.set(j, Math.min(res.get(j), res.get(j + 1)) + currentRow.get(j));
            }
        }
        return res.get(0);
    }
}

热门阅读


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Blog Design Solutions

Blog Design Solutions

Richard Rutter、Andy Budd、Simon Collison、Chris J Davis、Michael Heilemann、Phil Sherry、David Powers、John Oxton / friendsofED / 2006-2-16 / USD 39.99

Blogging has moved rapidly from being a craze to become a core feature of the Internetfrom individuals sharing their thoughts with the world via online diaries, through fans talking about their favori......一起来看看 《Blog Design Solutions》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具