[LeetCode] 64. Minimum Path Sum_Medium tag: Dynamic Programming

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 class Solution(object):
 2     def minPathSum(self, grid):
 3         # S; O(m*n)
 4         if not grid or len(grid[0]) == 0: return 0
 5         m, n = len(grid), len(grid[0])
 6         if m == 1 or n == 1: return sum(sum(each) for each in grid)
 7         ans = grid
 8         for i in range(m):
 9             for j in range(n):
10                 if i == 0 and j!= 0:
11                     ans[i][j] = ans[i][j-1] + grid[i][j]
12                 if j == 0 and i!= 0:
13                     ans[i][j] = ans[i-1][j] + grid[i][j]
14                 if j >0 and i >0 :
15                     ans[i][j] = min(ans[i-1][j], ans[i][j-1]) + grid[i][j]
16         return ans[-1][-1]

4. Test cases

[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9333748.html