[LeetCode] 64. Minimum Path Sum_Medium tag: Dynamic Programming
2018-07-19 06:52 Johnson_强生仔仔 阅读(272) 评论(0) 编辑 收藏 举报Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
其实这个题目的思路是跟[LeetCode] 62. Unique Paths_ Medium tag: Dynamic Programming很像, 只不过一个是步数, 一个是minimal sum而已. 还是可以用滚动数组的方法, 只是需要注意
初始化即可.
1. Constraints
1) [0*0] 最小
2. Ideas
Dynamic Programming T: O(m*n) S: O(n) optimal(using rolling array)
3. Code
1) S: O(m * n)
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i][j] = grid[i][j] elif i == 0: dp[i][j] = grid[i][j] + dp[i][j - 1] elif j == 0: dp[i][j] = grid[i][j] + dp[i - 1][j] else: dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]) return dp[-1][-1]
3) S: O(n)
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[0] * n for _ in range(2)] for i in range(m): for j in range(n): if i == 0 and j == 0: dp[i%2][j] = grid[i][j] elif i == 0: dp[i%2][j] = dp[i%2][j - 1] + grid[i][j] elif j == 0: dp[i%2][j] = dp[(i - 1)%2][j] + grid[i][j] else: dp[i%2][j] = grid[i][j] + min(dp[i%2][j - 1], dp[(i - 1)%2][j]) return dp[(m - 1)%2][-1]
4. Test cases
[ [1,3,1], [1,5,1], [4,2,1] ] Output: 7