leetcode: 64. Minimum Path Sum
来源:互联网 发布:seo h标签 编辑:程序博客网 时间:2024/06/06 15:33
Q
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:
[[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.
AC
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ sum = list(grid[0]) for j in xrange(1, len(grid[0])): sum[j] = sum[j - 1] + grid[0][j] for i in xrange(1, len(grid)): sum[0] += grid[i][0] for j in xrange(1, len(grid[0])): sum[j] = min(sum[j - 1], sum[j]) + grid[i][j] return sum[-1]# Time: O(m * n)# Space: O(m + n)class Solution2(object): def minPathSum(self, grid): sum = list(grid[0]) for j in xrange(1, len(grid[0])): sum[j] = sum[j - 1] + grid[0][j] for i in xrange(1, len(grid)): sum[0] += grid[i][0] for j in xrange(1, len(grid[0])): sum[j] = min(sum[j - 1], sum[j]) + grid[i][j] return sum[-1]if __name__ == "__main__": assert Solution().minPathSum([[0,1] ,[1,0]]) == 1 assert Solution().minPathSum([[1,3,1], [1,5,1], [4,2,1]]) == 7
阅读全文
0 0
- [LeetCode]64.Minimum Path Sum
- LeetCode --- 64. Minimum Path Sum
- LeetCode 64.Minimum Path Sum
- [Leetcode] 64. Minimum Path Sum
- [leetcode] 64.Minimum Path Sum
- [leetcode] 64.Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- 64. Minimum Path Sum LeetCode
- [LeetCode]64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- [leetcode] 64. Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- LeetCode *** 64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- 【leetcode】64. Minimum Path Sum
- Leetcode:64. Minimum Path Sum
- LeetCode-64.Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- leetcode: 62. Unique Paths
- window7下部署zookeeper、启动dubbo-admin
- leetcode: 63. Unique Paths II
- Shiro (五) Base64和Md5加密
- 201509-2 日期计算 ccf
- leetcode: 64. Minimum Path Sum
- Linux tree命令
- Aizu ALDS1_7_A Rooted Trees
- 如何解决未经处理的win32异常
- java.sql.SQLException: Value'0000-00-00'异常解决办法[转]
- 安装kali后必做工作
- leetcode: 65. Valid Number
- Leetcode_729. My Calendar I
- SpringBoot--打包成WAR