【leetcode】1289. Minimum Falling Path Sum II

题目如下:

Given a square grid of integers arr, a falling path with non-zero shifts is a choice of exactly one element from each row of arr, such that no two elements chosen in adjacent rows are in the same column.

Return the minimum sum of a falling path with non-zero shifts.

Example 1:

Input: arr = [[1,2,3],[4,5,6],[7,8,9]]
Output: 13
Explanation:
The possible falling paths are:
[1,5,9], [1,5,7], [1,6,7], [1,6,8],
[2,4,8], [2,4,9], [2,6,7], [2,6,8],
[3,4,8], [3,4,9], [3,5,7], [3,5,9]
The falling path with the smallest sum is [1,5,7], so the answer is 13.

Constraints:

  • 1 <= arr.length == arr[i].length <= 200
  • -99 <= arr[i][j] <= 99

解题思路:记dp[i][j]为第i行取第j个元素时,在0~i行区间内获得的最小值。那么显然有dp[i][j] = min(dp[i][j],dp[i-1][k] + arr[i][j]) ,其中j != k。这样的话时间复杂度是O(n),超时了。再仔细想想,其实对于任意一个j,在dp[i-1]中只要找出最小值即可,当然最小值的所在的列不能和j相同。那么只需要记录dp[i-1]行中的最小值和次小值,如果最小值的下标和j相同就取次小值,否则取最小值。

代码如下:

class Solution(object):
    def minFallingPathSum(self, arr):
        """
        :type arr: List[List[int]]
        :rtype: int
        """
        dp = [[float(‘inf‘)] * len(arr) for _ in arr]
        for i in range(len(arr)):
            dp[0][i] = arr[0][i]

        def getMin(arr):
            min_val = float(‘inf‘)
            min_inx = 0
            for i in range(len(arr)):
                if min_val > arr[i]:
                    min_val = arr[i]
                    min_inx = i
            return (min_val,min_inx)

        def getSecMin(arr,min_inx):
            sec_min_val = float(‘inf‘)
            sec_min_inx = 0
            for i in range(len(arr)):
                if i == min_inx:continue
                if sec_min_val > arr[i]:
                    sec_min_val = arr[i]
                    sec_min_inx = i
            return (sec_min_val,sec_min_inx)

        for i in range(1,len(arr)):
            min_val, min_inx = getMin(dp[i-1])
            sec_min_val, sec_min_inx = getSecMin(dp[i-1],min_inx)
            for j in range(len(arr)):
                if j == min_inx:
                    dp[i][j] = min(dp[i][j],dp[i-1][sec_min_inx] + arr[i][j])
                else:
                    dp[i][j] = min(dp[i][j], dp[i - 1][min_inx] + arr[i][j])
        return min(dp[-1])

原文地址:https://www.cnblogs.com/seyjs/p/12041890.html

时间: 2024-11-09 15:58:42

【leetcode】1289. Minimum Falling Path Sum II的相关文章

【LeetCode】Binary Tree Maximum Path Sum 解题报告

[题目] Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / 2 3 Return 6. [解析] 题意:在二叉树中找一条路径,使得该路径的和最大.该路径可以从二叉树任何结点开始,也可以到任何结点结束. 思路:递归求一条经过root的最大路径,这条路径可能是:

108th LeetCode Weekly Contest Minimum Falling Path Sum

Given a square array of integers A, we want the minimum sum of a falling path through A. A falling path starts at any element in the first row, and chooses one element from each row.  The next row's choice must be in a column that is different from t

【leetcode】Binary Tree Maximum Path Sum (medium)

Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. 找树的最大路径和 注意路径可以从任意点起始和结束. 我发现我真的还挺擅长树的题目的,递归不难.就是因为有个需要比较的量(最大和),所以需要再写一个函数. 因为路径可以从任意点起始和结束,所以每次递归的时候左右子树小于等于0的就可以不管了. #include <iostream> #include

【leetcode】Binary Tree Maximum Path Sum

Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example:Given the below binary tree, 1 / 2 3 Return 6. 用递归确定每一个节点作为root时,从root出发的最长的路径 在每一次递归中计算maxPath 1 /** 2 * Def

【LeetCode】209. Minimum Size Subarray Sum

Minimum Size Subarray Sum Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7,the subar

LeetCode 5129. 下降路径最小和 II Minimum Falling Path Sum II

地址 https://leetcode-cn.com/contest/biweekly-contest-15/problems/minimum-falling-path-sum-ii/ 题目描述给你一个整数方阵 arr ,定义「非零偏移下降路径」为:从 arr 数组中的每一行选择一个数字,且按顺序选出来的数字中,相邻数字不在原数组的同一列. 请你返回非零偏移下降路径数字和的最小值. 示例 1: 输入:arr = [[1,2,3],[4,5,6],[7,8,9]] 输出:13 解释: 所有非零偏移

【Leetcode】Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its bottom-up level order trave

【Leetcode】Median of Two Sorted Array II

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 非常经典的一个问题,如果直接查找中位数,即偶数约定向下取整,奇数就是严格的中位数,这个题目直接可以比较每个数组的mid来计算得到. 但是这个问题的需求更改为如果为偶数,则中

LeetCode 931. Minimum Falling Path Sum

Given a square array of integers A, we want the minimum sum of a falling path through A. A falling path starts at any element in the first row, and chooses one element from each row. The next row's choice must be in a column that is different from th