LeetCode Triangle(dp)
来源:互联网 发布:ubuntu kernel 编辑:程序博客网 时间:2024/06/07 22:58
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, wheren is the total number of rows in the triangle.
题意:给出一个三角形矩阵,求从顶部到底部的最短路径
思路:动态规划,用dp(x,y)表示从(0,0)到(x,y)的最短路径,f(x,y)表示元素值,则状态转移方程为
dp(x,y)=min{dp(x-1,y), dp(x, y -1)} + f(x,y)
代码如下:
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> tmp = new ArrayList<Integer>(); if (triangle.size() > 0) { tmp.add(triangle.get(0).get(0)); res.add(tmp); } for (int i = 0; i < triangle.size() - 1; i++) { tmp = new ArrayList<Integer>(); for (int j = 0; j < triangle.get(i).size(); j++) { int t1 = res.get(i).get(j) + triangle.get(i + 1).get(j); int t2 = res.get(i).get(j) + triangle.get(i + 1).get(j + 1); if (j >= tmp.size()) tmp.add(t1); else { int t = Math.min(t1, tmp.get(j)); tmp.set(j, t); } if (j + 1 >= tmp.size()) tmp.add(t2); else { int t = Math.min(t2, tmp.get(j + 1)); tmp.set(j + 1, t); } } res.add(tmp); } int n = res.size(); int ans = Integer.MAX_VALUE; for (int i = 0; i < res.get(n - 1).size(); i++) { ans = Math.min(ans, res.get(n - 1).get(i)); } return ans; }}
0 0
- Leetcode dfs&dp Triangle
- 【Leetcode】Triangle (DP)
- [leetcode][DP] Triangle
- LeetCode Triangle(dp)
- leetcode dp之Triangle
- (DP)LeetCode#120. Triangle
- leetcode---triangle---dp
- LeetCode Triangle 120 DP问题
- leetcode -- Triangle -- dp题目重点
- 【DP】Triangle
- DP Triangle
- Triangle ---DP
- 每日AC--LeetCode-Triangle -- 数塔问题DP
- LeetCode : Triangle
- [LeetCode] Triangle
- [Leetcode] Triangle
- [LeetCode] Triangle
- 【leetcode】Triangle
- 九度OJ-题目1520:树的子结构
- C语言函数声明
- 哈希表
- android-【DDMS->heap->MAT】工具-内存分析工具
- Imagick api中文翻译
- LeetCode Triangle(dp)
- 新GRE逻辑阅读作者的观念及文化背景解析
- web作用域
- 直接拿来用!最火的Android开源项目(完结篇)
- iOS中AutoLayer自动布局流程及相关方法
- array_multisort对select查询的二维数组排序
- [Erlang]如何添加自己的BIF
- Android开发PopupWindow.showAtLocation用法
- Innodb事务隔离级别