LeetCode(120):三角形最小路径和 Triangle(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅
本文介绍了如何使用动态规划解决LeetCode第120题,三角形最小路径和。通过自底向上的方法,建立dp数组,每个元素表示到达该位置的最小路径和。从最后一行开始,根据相邻元素更新dp数组,最终得到顶部的最小路径和。
摘要由CSDN通过智能技术生成

2019.12.22 LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

自底向上的动态规划。建立dp数组,dp[j]代表当前层j位置的最小路径和,对于每一层i,自底向上有动态转移方程:

dp[j] = triangle.get(i - 1).get(j) + Math.min(dp[j], dp[j + 1]);

传送门:三角形最小路径和

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

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

例如,给定三角形:
[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。

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


import java.util.List;

/**
 *
 * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
 * 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
 *
 */

public class Triangle {
    public int minimumTotal(List<List<Integer>> triangle) {
        int size = triangle.size();
        int[] dp = new int[size];
        for(int i = 0; i < size; i++){
            dp[i] = triangle.get(size - 1).get(i);
        }
        for(int i = size - 1; i >= 0; i--) {
            for(int j = 0; j < i; j++) {
                dp[j] = triangle.get(i - 1).get(j) + Math.min(dp[j], dp[j + 1]);
            }
        }
        return dp[0];
    }
}





#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值