zoukankan      html  css  js  c++  java
  • Java for LeetCode 120 Triangle

    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).

    解题思路:

    DP问题,用一个dp数组滚动下来即可,JAVA实现如下:

        public int minimumTotal(List<List<Integer>> triangle) {
    		int[] dp = new int[triangle.size()];
    		dp[0]=triangle.get(0).get(0);
    		if(triangle.size()>=2){
    			dp[1]=triangle.get(1).get(1)+dp[0];
    			dp[0]+=triangle.get(1).get(0);
    		}
    		for (int i=2;i<triangle.size();i++) {
    			int left = dp[0];
    			int right = dp[1];
    			dp[0] += triangle.get(i).get(0);
    			for (int j = 1; j <= i - 1; j++) {
    				dp[j] = triangle.get(i).get(j) + Math.min(left, right);
    				left = right;
    				right = dp[j + 1];
    			}
    			dp[i] = left + triangle.get(i).get(i);
    			left = dp[0];
    			right = dp[1];
    		}
    		for (int i = 0; i < dp.length - 1; i++)
    			if (dp[i] < dp[i + 1])
    				dp[i + 1] = dp[i];
    		return dp[dp.length - 1];
        }
    
  • 相关阅读:
    ExecuteScalar 返回值问题
    c#中怎么用for循环遍历DataTable中的数据
    select多用户之间通信
    python快速学习6
    python快速学习5
    python快速学习4
    python快速学习3
    python快速学习2
    arm处理器
    软链接与硬链接
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4527347.html
Copyright © 2011-2022 走看看