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

设状态为 f[i][j],表示根到节点(i,j)的最短路径,状态方程:
f[i][j] = min(f[i-1,j-1],f[i-1,j]) + tringal[i,j]
使用一维数组实现:

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int height = triangle.size();
        if(height == 0){
            return 0;
        }
        
        int [] minPath = new int[height+1];
        List<Integer> layer = triangle.get(0);
        minPath[0] = Integer.MAX_VALUE;
        minPath[1] = layer.get(0);
        int minPathValue = Integer.MAX_VALUE;
        for(int i = 1; i<height; i++){
            layer = triangle.get(i);
            minPath[i+1] = Integer.MAX_VALUE;
            for(int j=i+1; j>0; j--){
                minPath[j] = Math.min(minPath[j-1], minPath[j]) + layer.get(j-1);
            }
        }
        for(Integer i: minPath){
            minPathValue = Math.min(minPathValue, i);
        }
        
        return minPathValue;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,859评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,797评论 0 23
  • 课程目标 掌握常见 CSS 选择器的用法 对选择器优先级有一定认识 课程任务 1. CSS选择器常见的有几种? i...
    Timmmmmmm阅读 270评论 0 0
  • 如果还有可能,我还想来这,看看这个靠窗而坐的女孩,吃着苹果看着书。很恬!
    jac1king阅读 216评论 0 1
  • 中午休息,姜润和苏晓坐在一旁,翘起二踉腿,畅谈“美好未来”。 “你看看楼下一点点奶茶店,每天都排好长的队,营业额不...
    小星晨阅读 375评论 1 3

友情链接更多精彩内容