每日AC--LeetCode-Triangle -- 数塔问题DP
来源:互联网 发布:unity3d project 编辑:程序博客网 时间:2024/06/06 10:00
每日AC--LeetCode-Triangle -- 数塔问题DP
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 is11(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.
AC代码:
import java.util.ArrayList;import java.util.List;/** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年9月13日 Create this file * </pre> * */public class LeetCodeTringle { private static List<Integer> ansList = new ArrayList<Integer>(); // 对于这个,数塔问题, 考虑从 哪开始进行dp,规模缩小后计算 /** * 2 * 3 4 * 6 5 7 * 4 1 8 3 * 动态规划思想, 从哪开始算 倒数第二行开始算 * 行i 列 j 关系是 j <=i 理解这个三角关系 行列关系 * @param triangle * @return */ public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { // 这里稍微开辟个额外的空间赋值 for(int i = triangle.size()-2; i >=0; i--){ for(int j = 0; j <=i; j++){ // 从下往上 只有两种情况,比如说6 ,底部只有两种可能 要么从4来 那么就是 i+1,j 要么从1来 就是 i+1,j+1 int value = Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1)); triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i+1).get(j), triangle.get(i+1).get(j+1))); } } return triangle.get(0).get(0); } /** * @param args */ public static void main(String[] args) { ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmpList = new ArrayList<Integer>(); tmpList.add(2); triangle.add(tmpList); ArrayList<Integer> tmpList1 = new ArrayList<Integer>(); tmpList1.add(3); tmpList1.add(4); triangle.add(tmpList1); ArrayList<Integer> tmpList2 = new ArrayList<Integer>(); tmpList2.add(6); tmpList2.add(5); tmpList2.add(7); triangle.add(tmpList2); ArrayList<Integer> tmpList3 = new ArrayList<Integer>(); tmpList3.add(4); tmpList3.add(1); tmpList3.add(8); tmpList3.add(3); triangle.add(tmpList3); int ans = new LeetCodeTringle().minimumTotal(triangle); System.out.println(ans); System.out.println(ansList); }}
阅读全文
0 0
- 每日AC--LeetCode-Triangle -- 数塔问题DP
- LeetCode Triangle 120 DP问题
- HLG 1004 The Triangle(数塔问题DP)
- POJ 1163 The Triangle(DP 数塔问题)
- 每日AC -数串
- 每日AC--leetcode--recordList
- 每日AC--LeetCode-Candy
- POJ The Triangle (dp数塔)
- FZU 1004 Number Triangle【数塔dp】
- Leetcode dfs&dp Triangle
- 【Leetcode】Triangle (DP)
- [leetcode][DP] Triangle
- LeetCode Triangle(dp)
- leetcode dp之Triangle
- (DP)LeetCode#120. Triangle
- leetcode---triangle---dp
- 每日AC--gas-station--LeetCode
- NYOJ-The Triangle【数塔问题】
- 少儿python海龟画图编程汉化增强版说明档案 (turtle库中文翻译)
- leetcode-- two sum
- CCF——火车购票
- mqtt实现自动监听服务器消息
- ssh经典面试题
- 每日AC--LeetCode-Triangle -- 数塔问题DP
- UID 自动生成ID
- iOS 11 将于9月19日正式发布,一文带你了解它的那些特性
- ArcGIS Engine空间查询之高亮显示和非高亮显示的实现
- Java中的方法小结
- redis学习之集群报错Node is not empty
- 一位资深程序员大牛给予Java初学者的学习路线建议
- 外观模式
- sql处理小技巧