返回

征服 LeetCode - #120:揭秘三角形最小路径和

IOS

前言

在本文中,我们将深入剖析三角形最小路径和问题,并逐步构建一个清晰、高效的解决方案。我们还会深入探讨动态规划的概念,以及它如何帮助我们解决这类问题。

理解问题

给定一个三角形,其中每个元素代表一个整数,要求我们找到从三角形顶点到底部的最小路径和。换句话说,我们要找到一条路径,从三角形顶点出发,经过三角形中的某些元素,最后到达三角形底部,并且这条路径上的元素和最小。

动态规划的魔力

动态规划是一种用于解决最优化问题的技术。它将问题分解成更小的子问题,并以一种自底向上的方式逐步解决这些子问题。对于三角形最小路径和问题,我们可以将问题分解成如下子问题:

  • 找到从三角形顶点到第 i 行的最小路径和。
  • 找到从三角形第 i 行到第 i+1 行的最小路径和。

通过逐层解决这些子问题,我们可以最终找到从三角形顶点到底部的最小路径和。

代码实现

以下是如何使用动态规划解决三角形最小路径和问题的 Python 代码:

def minimum_path_sum(triangle):
  """
  Finds the minimum path sum from the top to the bottom of a triangle.

  Args:
    triangle: A list of lists of integers representing the triangle.

  Returns:
    The minimum path sum.
  """

  # Initialize the dp table with the first row of the triangle.
  dp = triangle[0]

  # Iterate over the remaining rows of the triangle.
  for i in range(1, len(triangle)):
    # For each element in the current row, update the dp table.
    for j in range(len(triangle[i])):
      # If the current element is on the left edge, the minimum path sum is the sum of the current element and the element above it.
      if j == 0:
        dp[j] = triangle[i][j] + dp[j]
      # If the current element is on the right edge, the minimum path sum is the sum of the current element and the element above it.
      elif j == len(triangle[i]) - 1:
        dp[j] = triangle[i][j] + dp[j - 1]
      # Otherwise, the minimum path sum is the sum of the current element and the smaller of the two elements above it.
      else:
        dp[j] = triangle[i][j] + min(dp[j - 1], dp[j])

  # Return the minimum path sum.
  return min(dp)

总结

三角形最小路径和问题是一个经典的动态规划问题。通过将问题分解成更小的子问题并使用动态规划技术,我们可以有效地解决这个问题。动态规划是一种强大的技术,它可以用于解决许多最优化问题。