LeetCode - #64 Minimum Path Sum (Top 100)

Get into the habit of writing together! This is the 10th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

This question is the top 100 high frequency questions of LeetCode

Our community will successively organize Gu Yi ( Netflix growth hacker, author of "The Way of the iOS Interview", ACE professional fitness coach. )'s Swift algorithm problem solutions into a text version for everyone to learn and read.

We have updated the LeetCode algorithm for 63 issues so far, and we will keep the update time and progress ( released at 9:00 am on Monday, Wednesday, and Friday ). There will be a big improvement.

If you don't accumulate a small step, you can't go a thousand miles; if you don't accumulate a small stream, you can't make a river. The Swift community accompanies you to move forward. If you have suggestions and comments, please leave a message at the end of the article, we will try our best to meet your needs.

Difficulty level: medium

1. Description

Given a m x ngrid grid, find a path from the upper left corner to the lower right corner such that the sum of the numbers on the path is the smallest.

Description: You can only move down or to the right one step at a time.

2. Example

Example 1

输入:grid = [[1,3,1],[1,5,1],[4,2,1]]
输出:7
解释:因为路径 1→3→1→1→1 的总和最小。
复制代码

Example 2

输入:grid = [[1,2,3],[4,5,6]]
输出:12
复制代码

Restrictions:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 100

3. Answers

class MinimumPathSum {
    func minPathSum(_ grid: [[Int]]) -> Int {
        guard grid.count != 0 && grid[0].count != 0 else{
            return 0
        }
    
        let m = grid.count, n = grid[0].count
        var dp = Array(repeating: Array(repeating: 0, count: n), count: m)
        
        for i in 0..<m {
            for j in 0..<n {
                if i == 0 && j == 0{
                    dp[i][j] = grid[i][j]
                } else if i == 0 {
                    dp[i][j] = dp[i][j - 1] + grid[i][j]
                } else if j == 0 {
                    dp[i][j] = dp[i - 1][j] + grid[i][j]
                } else {
                    dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
                }
            }
        }
        
        return dp[m - 1][n - 1]
    }
}
复制代码
  • Main idea: Classical 2D dynamic programming.
  • Time Complexity: O(mn)
  • Space Complexity: O(mn)

Repository for the algorithm solution: LeetCode-Swift

Click to go to LeetCode practice

about us

We are jointly maintained by Swift enthusiasts. We will share the technical content centered on Swift combat, SwiftUI, and Swift foundation, and also organize and collect excellent learning materials.

Guess you like

Origin juejin.im/post/7085923212579569678