120.Triangle
2016-05-06 11:18
483 查看
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
The minimum path sum from top to bottom is
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.
采用动态规划的思想,自底向上做,需要修改给定的数组的值,triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]),修改后的triangle[i][j]表示从最底层到第i层第j个元素的路径上的最小值。
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.
采用动态规划的思想,自底向上做,需要修改给定的数组的值,triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]),修改后的triangle[i][j]表示从最底层到第i层第j个元素的路径上的最小值。
/**@author * 给定一个三角形,找到从第一行到最后一行上的最短路径。当前行的元素只能走到下一行中与其相邻的元素。 * 采用动态规划的思想,自底向上做,需要修改给定的数组的值,triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]) * 修改后的triangle[i][j]表示从最底层到第i层第j个元素的路径上的最小值。 * * 题目中假设输入的参数合法。 * @date 20160505 */ public int minimumTotal(List<List<Integer>> triangle) { int rowSize = triangle.size(); List<Integer> list = null;//表示在循环中读到的那一行。 for(int i=rowSize-2;i>=0;i--){//从倒数第二行开始计算 list = triangle.get(i); for(int index = list.size()-1;index>=0;index--){ int min = Math.min(triangle.get(i+1).get(index), triangle.get(i+1).get(index+1)); list.set(index, list.get(index)+min); } } return triangle.get(0).get(0); }
相关文章推荐
- 教你快速写出多线程Junit单元测试用例 - GroboUtils
- centos jenkins
- ArcGIS相关帮助网址大全
- UITextField左侧的表达图片(..我也不知道叫什么)
- Python 迭代器工具包【推荐】
- 重读java编程思想之访问权限控制二
- 你应该知道的HTTP基础知识
- 2016年4月27日作业(论文)
- PHP递归遍历多维数组实现无限分类的方法
- 镭射激光HSL-4000III二次开发
- bootstrap制作导航条
- 快速排序里的学问:再看看称球问题
- Java 如何有效地避免OOM:善于利用软引用和弱引用
- jquery form 表单ajax提交使用
- Java中的多态的用途
- H.264整数DCT公式推导及蝶形算法分析
- [团队项目] Scrum 项目 2.0 产品BACKLOG
- 解决Linux中文显示乱码的问题
- c#省市联动
- HTML5 input元素新的特性