每日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);    }}