[leetcode] Minimum Path Sum
生活随笔
收集整理的這篇文章主要介紹了
[leetcode] Minimum Path Sum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Minimum Path Sum
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. 分析:動態規劃: 狀態轉移公式為:ret[i][j] = min(ret[i-1][j], ret[i][j-1]) + grid[i][j]; 對于矩陣| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
| 1 | 1+2 | 1+2+3 |
| 1+4 | 1+2+5 | 1+2+3+6 |
| 1+4+7 | 1+2+5+8 | 1+2+3+6+9 |
| 1 | 3 | 6 |
| 5 | 8 | 12 |
| 12 | 16 | 21 |
1 class Solution 2 { 3 public: 4 int minPathSum(vector<vector<int> > &grid) 5 { 6 if(grid.size() == 0) 7 return 0; 8 9 vector<vector<int> > ret(grid); 10 11 for(int i=1; i<grid.size(); i++) 12 ret[i][0] += ret[i-1][0]; 13 14 for(int j=1; j<grid[0].size(); j++) 15 ret[0][j] += ret[0][j-1]; 16 17 for(int i=1; i<grid.size(); i++) 18 for(int j=1; j<grid[i].size(); j++) 19 ret[i][j] = min(ret[i][j-1], ret[i-1][j]) + grid[i][j]; 20 21 return ret[grid.size()-1][grid[0].size()-1]; 22 } 23 };
?
轉載于:https://www.cnblogs.com/lxd2502/p/4371061.html
總結
以上是生活随笔為你收集整理的[leetcode] Minimum Path Sum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最酷的微信网名
- 下一篇: 予一的胸牌、奖杯等是什么做的,大概多少钱