LeetCode 64. Minimum Path Sum---Python实现
2018-01-16 15:13
429 查看
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 1:
Given the above grid map, return
Because the path 1→3→1→1→1 minimizes the sum.
这个文章和前两题一样都是典型的动态规划问题。主要是找出grid[i][j]=grid[i][j]+min(grid[i-1][j],grid[i][j-1])递推关系式,这里加个min判断就行了。class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m,n=len(grid),len(grid[0])
for i in range(1,n):
grid[0][i]+=grid[0][i-1] #第一行赋值
for j in range(1,m):
grid[j][0]+=grid[j-1][0] #第一列赋值
for i in range(1,m): #从1开始就行,
for j in range(1,n):
grid[i][j]=grid[i][j]+min(grid[i-1][j],grid[i][j-1])
return grid[m-1][n-1]
Note: You can only move either down or right at any point in time.
Example 1:
[[1,3,1], [1,5,1], [4,2,1]]
Given the above grid map, return
7.
Because the path 1→3→1→1→1 minimizes the sum.
这个文章和前两题一样都是典型的动态规划问题。主要是找出grid[i][j]=grid[i][j]+min(grid[i-1][j],grid[i][j-1])递推关系式,这里加个min判断就行了。class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m,n=len(grid),len(grid[0])
for i in range(1,n):
grid[0][i]+=grid[0][i-1] #第一行赋值
for j in range(1,m):
grid[j][0]+=grid[j-1][0] #第一列赋值
for i in range(1,m): #从1开始就行,
for j in range(1,n):
grid[i][j]=grid[i][j]+min(grid[i-1][j],grid[i][j-1])
return grid[m-1][n-1]
相关文章推荐
- LeetCode 64 Minimum Path Sum(Python详解及代码实现)
- 【leetCode】Path Sum II python实现
- LeetCode 112 — Path Sum(C++ Java Python)
- [LeetCode]1 Two Sum(C++,Python实现)
- LeetCode -- Path Sum III分析及实现方法
- 【Leetcode】【python】Minimum Path Sum
- [LeetCode]题解(python):124-Binary Tree Maximum Path Sum
- [leetcode]Minimum Path Sum @ Python
- 【LeetCode-面试算法经典-Java实现】【112-Path Sum(路径和)】
- [python]leetcode(437). Path Sum III
- leetcode解题之62&63. Unique Paths ||64. Minimum Path Sum java版(路径(最短)可达)
- LeetCode--437. Path Sum III(路径和)Python
- leetcode-Two sum(最佳思路以及python代码实现)
- LeetCode-64-Minimum Path Sum(C语言实现)
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】
- [Leetcode][python]Binary Tree Maximum Path Sum
- [leetcode] 64. Minimum Path Sum 解题报告
- 【LeetCode with Python】 Binary Tree Maximum Path Sum
- LeetCode 64 — Minimum Path Sum(C++ Java Python)
- LeetCode 64. Minimum Path Sum 解题报告