leetcode #64 in cpp
来源:互联网 发布:mysql判断崩溃 编辑:程序博客网 时间:2024/05/17 02:13
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.
Solution:
We use DP where dp[i][j] = minimum sum along the path from position(i+1,j+1) to the destination.
Then dp[i][j] = min(dp[i+1][j], dp[i][j+1]) + grid[i][j]. That is, we select the direction which gives us a smaller sum, when we decide to take the next step.
Code:
class Solution {public: int minPathSum(vector<vector<int>>& grid) { int m = grid.size(); int n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n,0)); dp[m-1][n-1] = grid[m-1][n-1]; for(int i = m-2; i >= 0; i --){//right border dp[i][n-1] = grid[i][n-1] + dp[i+1][n-1]; } for(int i = n-2; i >= 0; i--){//bottom border dp[m-1][i] = grid[m-1][i]+dp[m-1][i+1]; } for(int i = m-2; i >= 0; i --){ for(int j = n-2; j>=0; j --){ dp[i][j] = min(dp[i+1][j], dp[i][j+1])+grid[i][j];//compare results from turning right and turning down } } return dp[0][0]; }};
One optimization is to update the sum in place in grid instead of using the dp arrays. This saves us some memory.
0 0
- leetcode #64 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- poj1050
- 自定义UITableView,实现cell的三级分组展开收起
- 移动端开发调试工具,别点,就两个链接而已
- PDF转Word转换器
- 我的struts2学习之一
- leetcode #64 in cpp
- 思
- 迷宫最短路径问题(ShortestPath)的求解——利用链式队列
- HDU1301 普里姆最小生成树
- [Android基础]Android总结篇
- 屏幕键盘开启占用COM1的问题?
- 序列化
- java中的单例模式
- .CodeforcesBeta Round #19 D. Points 线段树 单点更新