LeetCode -- Triangle
来源:互联网 发布:名人朋友圈刷圈币软件 编辑:程序博客网 时间:2024/06/05 04:03
题目描述:
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).
求三角形从上到下构成最小值的和的路径。
思路:
1.使用一个辅助的二维数组保存当前[i,j]的最小和,再遍历一次最后一层的值从而得到最小值。
2.在求和过程中,区分收尾字符和中间字符的情况。
假设arr[i,j]来保留第i行第j列的最小和。则:
arr[0,0] = triangle[0,0];
当j为中间元素:
arr[i,j] = Min(arr[i-1,j], arr[i-1,j-1]) + triangle[i,j]
当j为首元素:
arr[i,0] = arr[i-1,0] + triangle[i,0]
当j为末尾元素:
arr[i,count-1] = arr[i-1,count-2] + triangle[i,count-1]
实现代码:
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).
求三角形从上到下构成最小值的和的路径。
思路:
1.使用一个辅助的二维数组保存当前[i,j]的最小和,再遍历一次最后一层的值从而得到最小值。
2.在求和过程中,区分收尾字符和中间字符的情况。
假设arr[i,j]来保留第i行第j列的最小和。则:
arr[0,0] = triangle[0,0];
当j为中间元素:
arr[i,j] = Min(arr[i-1,j], arr[i-1,j-1]) + triangle[i,j]
当j为首元素:
arr[i,0] = arr[i-1,0] + triangle[i,0]
当j为末尾元素:
arr[i,count-1] = arr[i-1,count-2] + triangle[i,count-1]
实现代码:
public class Solution { public int MinimumTotal(IList<IList<int>> triangle) { if(triangle.Count == 0){ return 0; } if(triangle.Count == 1){ return triangle[0][0]; } var arr = new int[triangle.Count, triangle[triangle.Count - 1].Count]; arr[0,0] = triangle[0][0]; for(var i = 1;i < triangle.Count; i++) { var current = triangle[i]; arr[i,0] = current[0] + arr[i-1,0]; for(var j = 1;j < current.Count - 1; j++) { arr[i,j] = current[j] + Math.Min(arr[i-1,j],arr[i-1,j-1]); } arr[i,current.Count-1] = current[current.Count-1] + arr[i-1,current.Count-2]; } var len = arr.GetLength(1); var min = arr[len - 1,0]; for(var i = 1;i < len; i++){ if(min > arr[len - 1,i]){ min = arr[len - 1,i]; } } return min; }}
1 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
- WiFi信息获取简单demo
- oracle中in和exists区别
- GRE考试中七个阻碍【zhasite】
- Solaris Zpool 创建文件系统
- 【AJAX】给你不一样的用户体验
- LeetCode -- Triangle
- Android_收回键盘
- 使用PHPexcel把excel数据导入数据库
- BOS里如何DEP分录字段
- 比较方便的一种点击事件处理
- Android的广播使用
- touchscreen的B协议上报部分
- 用过的pod
- android——material design实现Tab标签