zoukankan      html  css  js  c++  java
  • [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).

    https://oj.leetcode.com/problems/triangle/

    思路:DP,从最底层递推上去。dp[i][j]表示第i层j个元素为起点的最小路径和。

      递推公式:dp[i][j]=value[i][j]+min{dp[i+1][j],dp[i+1][j+1};

      因为每一层只跟下一层相关,所以只需一维状态即可。

    public class Solution {
        public int minimumTotal(List<List<Integer>> triangle) {
            int n = triangle.size();
            int[] dp = new int[n]; // dp[i] 代表从下到第i层最小的路径和
            for (int i = n - 1; i >= 0; i--) {
                for (int j = 0; j <= i; j++) {
                    if (i == n - 1)
                        dp[j] = triangle.get(i).get(j);
                    else
                        dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
                }
            }
    
            return dp[0];
    
        }
    
        public static void main(String[] args) {
            List<List<Integer>> triangle = new ArrayList<List<Integer>>();
            triangle.add(Arrays.asList(new Integer[] { 2 }));
            triangle.add(Arrays.asList(new Integer[] { 3, 4 }));
            triangle.add(Arrays.asList(new Integer[] { 6, 5, 7 }));
            triangle.add(Arrays.asList(new Integer[] { 4, 1, 8, 3 }));
    
            System.out.println(new Solution().minimumTotal(triangle));
        }
    }

     第二遍记录:

    先画二维的,然后根据递推顺序转化成一维的。

    第三遍记录:

      二维和一维都要注意纵坐标的范围,不要越界。

      一维递推的时候注意要 自下而上,自左而右。

  • 相关阅读:
    Vim step by step
    Ubuntu解压命令全览
    这样才能使本地Mysql服务允许被外部主机连接(两步)
    [Python] logging.logger
    Python Selenium
    MySQL中char、varchar和text的区别
    Way to MongoDB
    Python误区之strip,lstrip,rstrip
    Android Studio Tips
    Way to tmux
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3823362.html
Copyright © 2011-2022 走看看