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

    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.

    题意:数塔求最小的路径和是多少。

    思路:数塔的DP思想。为了最好还是碍后面的计算。我们每行计算从后面開始。

    public class Solution {
        public int minimumTotal(List<List<Integer>> triangle) {
            int n = triangle.size();
        	if (n == 0) return 0;
        	
        	int f[] = new int[triangle.size()];
        	f[0]=  triangle.get(0).get(0);
        	for (int i = 1; i < triangle.size(); i++) 
        		for (int j = triangle.get(i).size()-1; j >= 0; j--) {
        			if (j == 0) 
        				f[j] = f[j] + triangle.get(i).get(j);
        			else if (j == triangle.get(i).size() - 1) 
        				f[j] = f[j-1] + triangle.get(i).get(j);
        			else f[j] = Math.min(f[j-1], f[j]) + triangle.get(i).get(j); 
        		}
        	
        	int ans = Integer.MAX_VALUE;
        	for (int i = 0; i < f.length; i++)
        		ans = Math.min(ans, f[i]);
        	
        	return ans;
        }
    }


  • 相关阅读:
    Java 浮点数精度丢失
    旧梦。
    luogu6584 重拳出击
    luogu1758 [NOI2009]管道取珠
    luogu4298 [CTSC2008]祭祀
    bzoj3569 DZY Loves Chinese II
    AGC006C Rabbit Exercise
    bzoj1115 [POI2009]石子游戏Kam
    luogu5675 [GZOI2017]取石子游戏
    bzoj3143 [HNOI2013]游走
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6802643.html
Copyright © 2020-2023  润新知