zoukankan      html  css  js  c++  java
  • 2020.7.14 刷题

    120. 三角形最小路径和

    动态规划,自底向上

    dp[i][j] :表示从i, j到底边的最小距离

    dp[i][j] = min (dp[i+1][j] , dp[i+1][j+1]) + triangle[i][j]

    java:

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

    空间优化,因为只需要记一组数据,辅助空间只要一个一维数组

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

    python 3:

    class Solution:
        def minimumTotal(self, triangle: List[List[int]]) -> int:
            dp = triangle[-1]
            n = len(triangle)
            for i in range(n-2, -1, -1):
                for j in range(0, i+1):
                    dp[j] = min(dp[j], dp[j+1]) + triangle[i][j]
            return dp[0]

    11. 盛最多水的容器

    class Solution {
         public int maxArea(int[] height) {
            int n = height.length;
            if(n <= 1) return 0;
            if(n == 2) return Math.min(height[0], height[1]);
            int i = 0, j = n - 1;
            int max = 0;
            while(i < j){
                max = Math.max(max, Math.min(height[i], height[j]) * (j - i));
                if (height[i] < height[j]) {
                    i++;
                } else {
                    j--;
                }
            }
            return max;
        }
    }

    python

    class Solution:
        def maxArea(self, height: List[int]) -> int:
            n = len(height)
            if n < 2 :
                return 0
            elif n == 2:
                return min(height[0], height[1])
            i, j, res = 0, n-1, 0
            while i < j :
                res = max(res, min(height[i], height[j]) * (j - i) )
                if height[i] < height[j]:
                    i += 1
                else:
                    j -= 1
            return res
  • 相关阅读:
    Unity The Method Signature Matching Rule
    Unity The Property Matching Rule
    Unity The Type Matching Rule
    Unity The Custom Attribute Matching Rule
    Unity The Member Name Matching Rule
    Unity No Policies
    Unity The Return Type Matching Rule
    Unity The Parameter Type Matching Rule
    Unity The Namespace Matching Rule
    关于TSQL递归查询的(转)
  • 原文地址:https://www.cnblogs.com/shish/p/13297974.html
Copyright © 2011-2022 走看看