Leetcode 120. Triangle 三角形问题(动态规划经典) 解题报告
来源:互联网 发布:淘宝怎么搜索关键词 编辑:程序博客网 时间:2024/05/16 12:41
1 解题报告
首先我承认我很二哈,这道题我明明已经做过了,但是刚刚不知道为什么又去做了一遍,而且我查了下两次的解法还有所差别(貌似是现在的版本有进步了呢)
问题就是一个三角形的数组,求从顶部到下方的最短路径。。
这个问题是太过经典+Easy的DP问题了,哈哈。。
不想多讲,直接看吧
PS:其实这道题倒着从底部到顶部也可以
2 原题
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. Subscribe to see which companies asked this question
3 今天做的版本
今天做的版本我着重写了下注释,而且用的方法更加省内存了~~
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { /* 典型的动态规划问题 对于层数i的第j个节点有:dp[i][j] = triangle[i][j] + min(dp[i-1][j-1],dp[i-1][j]) (注意特殊处理边界) 改善:只使用O(n)的弓箭,那么就只弄一层,使用一个lastVal来代替dp[i-1][j-1] */ int n = triangle.size(); int dp[] = new int[n]; //第一个为0 其他为max for(int i=1;i<n;i++) dp[i] = Integer.MAX_VALUE; int lastVal,tmp; for(int i=0;i<n;i++){ lastVal = Integer.MAX_VALUE; for(int j=0;j<=i;j++){ tmp = dp[j]; dp[j] = triangle.get(i).get(j) + Math.min(dp[j],lastVal); lastVal = tmp; } } int res = Integer.MAX_VALUE; for(int i=0;i<n;i++) res = Math.min(res,dp[i]); return res; }}
4 很久前做的版本
public class Solution { public int minimumTotal(List<List<Integer>> triangle) { if(triangle.size()==0) return 0; int dp[]=new int[triangle.size()]; int last[]=new int[triangle.size()]; int tmp[]; dp[0]=triangle.get(0).get(0); last[0]=triangle.get(0).get(0); for(int i=1;i<triangle.size();i++){ List<Integer> line=triangle.get(i); dp[0]=line.get(0)+last[0]; dp[i]=line.get(i)+last[i-1]; for(int j=1;j<i;j++){ dp[j]=Math.min(last[j],last[j-1])+line.get(j); } tmp=last; last=dp; dp=tmp; } int result=last[0]; for(int i=1;i<triangle.size();i++){ result=Math.min(result,last[i]); } return result; }}
0 0
- Leetcode 120. Triangle 三角形问题(动态规划经典) 解题报告
- leetcode 120.Triangle-杨辉三角形|动态规划
- [leetcode] 120. Triangle 解题报告
- LeetCode 120. Triangle 解题报告
- LeetCode 120. Triangle 解题报告
- [Leetcode] 120. Triangle 解题报告
- 杭电OJ1466动态规划经典题(解题报告)
- Leetcode Triangle 解题报告
- 【LeetCode】Triangle 解题报告
- [LeetCode] Triangle 解题报告
- LeetCode 120. Triangle 动态规划
- LeetCode 120. Triangle 动态规划
- LeetCode解题报告 120. Triangle [medium]
- LeetCode -- Triangle 路径求最小和( 动态规划问题)
- 0-1背包问题(动态规划) 解题报告
- LeetCode 120. Triangle(三角形)
- [LeetCode] [动态规划] Triangle
- leetcode-动态规划:Triangle
- OI 字符串 常用哈希方法
- 如何将证书导入java默认的证书cacerts
- [LeetCode-100]Same Tree(java)
- Find Q
- Unbuntu16.04上用CMake图形界面交叉编译树莓派的OpenCV3.0
- Leetcode 120. Triangle 三角形问题(动态规划经典) 解题报告
- hash的基本原理
- 【字符串】字符串的全排列
- 代码访问mysql的时候,提示访问的表不存在,具体原因在这里
- java程序员面试笔试题(六)
- codeforces 723 A,B,C,D
- 【DP 训练】Alibaba, ACM/ICPC SEERC 2004, UVa1632
- 2016年四川省TI杯电子设计竞赛B题
- 浙大 PAT b1041