[LeetCode]Triangle
来源:互联网 发布:sql创建存储过程 查询 编辑:程序博客网 时间:2024/05/20 11:24
题目描述
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.
解题思路
通过题目的要求额外空间是O(n)我们可以分析得出,这O(n)的空间对应于最后一行每个数的路径和。
观察三角形结构可以知道,sum[i,0]和sum[i,row(i).length- 1]分别只和sum[i-1,0]和sum[i-1,row(i - 1).length- 1]相关,而sum[i,j]则是sum[i-1,j-1]+value(i,j)和sum[i-1,j]+value(i,j)的最小值。因此我们只需用一个一维数组保存当前行的sum值,便可求得下一行的sum值。
需要注意的:
在具体解题中,求sum数组时最好采用从后往前更新的方法,即先求sum[i,row(i ).length- 1]直到求出sum[i,0]。如果你采用先求sum[i,0]再循环求到sum[i,row(i ).length- 1]则需要添加额外的变量。因为这样循环,当前值会覆盖上一行的相应值。
代码
public static int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {int[] total = new int[triangle.size()];Arrays.fill(total, 0);for (int i = 0; i < triangle.size(); i++) {ArrayList<Integer> rowList = triangle.get(i);for (int j = rowList.size() - 1; j >= 0; j--) {if (j == 0 ) {total[j] += rowList.get(j);} else if (j == rowList.size() - 1) {total[j] = total[j-1] + rowList.get(j);} else {total[j] = Math.min(total[j-1] + rowList.get(j), total[j]+ rowList.get(j));}}}int min = total[0];for (int i = 1; i < total.length; i++) {if (total[i] < min)min = total[i];}return min;}
0 0
- LeetCode : Triangle
- [LeetCode] Triangle
- [Leetcode] Triangle
- [LeetCode] Triangle
- 【leetcode】Triangle
- LeetCode - Triangle
- [LeetCode]Triangle
- [Leetcode]Triangle
- [leetcode]Triangle
- Leetcode: Triangle
- [LeetCode] Triangle
- LeetCode-Triangle
- [leetcode] Triangle
- [LeetCode] Triangle
- LeetCode - Triangle
- 【Leetcode】Triangle
- LeetCode | Triangle
- [leetcode]Triangle
- UVA 10161-Ant on a Chessboard 简单模拟
- 1. 总是从ID选择器开始继承 在jquery中最快的选择器是ID选择器. 因为它直接来自于Javascript的getElementById()方法. Traffic Light
- STM32 启动汇编程序详解(复制过来的自己留着慢慢看)
- 锤子手机:历时两年精心准备的“笑话”
- java中常用名词的英文缩写释义
- [LeetCode]Triangle
- C++输入日期判断是星期几
- ListView,GridView,Gallery的Adapter中的getView多次调
- 活着,本身就是最美的事 唯美生活生命感悟美文
- SecureCRT 中 Git 彩色显示
- c# webBrowser全掌握
- 点击按钮显示ProgressDialog对话框
- DirectX 学习三:抽取要渲染的物体
- C++ 虚函数表解析