Middle-题目60:120. Triangle

原创 2016年05月31日 16:31:10

题目原文:
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).
题目大意:
给出一个三角形,求出从顶点到底边路径的最小值,每次只能向下移动到相邻的元素上。
分析:
令dp[i][j]代表从顶点走到[I,j]点的最小和,那么要么是从正上方来的,要么是从左上方来的,故有:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-1])+triangle[i][j],对两边的特殊讨论一下。
最后再对最后一行的dp值取最小值。
源码:(language:java)

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

成绩:
5ms,beats 57.96%,众数4ms,23.76%
Cmershen的碎碎念:
这道题在本科的《算法设计与分析》课上学过原题,可见是一个很经典也很有代表性的DP问题。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode 120 Triangle

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

Leetcode 120 Triangle 三角形最小路径和

给出一个三角形(数据数组),找出从上往下的最小路径和。每一步只能移动到下一行中的相邻结点上。空间复杂度要求O(n)。

leetcode_question_120 Triangle

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

[leetcode]120. Triangle(Java)

https://leetcode.com/problems/triangle/#/description Given a triangle, find the minimum pat...

LeetCode 120. Triangle 解题报告

LeetCode 120. Triangle 解题报告题目描述Given a triangle, find the minimum path sum from top to bottom. Each ...

【LeetCode-面试算法经典-Java实现】【120-Triangle(三角形)】

【120-Triangle(三角形)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a triangle, find the minimum path sum...

LeetCode 120. Triangle 动态规划

120. Triangle Given a triangle, find the minimum path sum from top to bottom. Each step you may mo...

leetcode120. Triangle

120. TriangleGiven a triangle, find the minimum path sum from top to bottom. Each step you may move ...

120. Triangle\57. Insert Interval\84. Largest Rectangle in Histogram*

Triangle 题目描述 代码实现 Insert Interval 题目描述 代码实现 Largest Rectangle in Histogram 题目描述 代码描述120. Triangle题目...

【leetcode】120. Triangle

Difficulty:medium Given a triangle, find the minimum path sum from top to bottom. Each step you m...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)