[leetcode64]Minimum Path Sum
2015-09-25 13:25
399 查看
问题描述:
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.
算法:
我首先想到的是利用优先队列进行搜索。import heapq class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ endx = len(grid) - 1 endy = len(grid[0]) - 1 priority_que = [(grid[0][0], (0,0))] while True: curSum, point = heapq.heappop(priority_que) if point == (endx,endy): return curSum curX,curY = point successors = [(x,y)for (x,y) in [(curX+1, curY), (curX, curY+1)] if x<=endx and y<=endy] for x,y in successors: if (x,y) == (endx,endy): return curSum+grid[x][y] else: heapq.heappush(priority_que, (curSum+grid[x][y],(x,y)))
但是,提交代码后发现超时。
这时,首先想到的是动态规划。
状态转移方程为 func(x,y) = min(func(x-1,y),func(x,y-1))+grid(x,y)
使用矩阵存储从起点到当前位置的路径最小值,从最上面一层以及最左面一层,逐渐递推到结束位置。
class Solution(object): def minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ endx = len(grid) endy = len(grid[0]) path = [[0 for _ in range(endy)] for _ in range(endx)] path[0][0] = grid[0][0] # get up line ready for i in range(1, endy): path[0][i] = path[0][i-1] + grid[0][i] # get left line ready for i in range(1, endx): print(path) print(i) path[i][0] = path[i-1][0] + grid[i][0] for r in range(1, endx): for c in range(1, endy): path[r][c] = min(path[r-1][c], path[r][c-1]) + grid[r][c] return path[endx-1][endy-1]
相关文章推荐
- 深入浅出UML类图(三)
- 2015年工作中遇到的问题:11-20
- 小题精炼-----初试C语言
- 黑马程序员_JAVA获取网页源代码
- shell以及sed awk总结
- 流水号算法
- 黑马程序员————java实现冒泡排序
- UI框架
- 新手如何配置spring
- Hzau—wireless有限的访问权限
- matlab中的sum函数的用法
- php学习基础篇之框架集 frameset
- Machine Learning笔记(二) 单变量线性回归
- windows7共享文件给vmware虚拟机中的Linux系统教程
- Root Container #Facebook Relay文档翻译#
- 怎么样提高观察力?
- C++隐式转换各种发生情况
- Struts2标签<s:checkboxlist>回显问题
- oracle,sqlserver,mysql三种数据库连接Demo
- Struts2标签<s:checkboxlist>回显问题