LeetCode64 Minimum Path Sum
Posted wangxiaobao的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode64 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.(Medium)
分析:
矩阵型动态规划,dp[i][j]表示到达i,j位置的。。。。
所以本题中dp[i][j]表示到达grid[i][j]的最小和。dp[i][j] = dp[i -1][j] + dp[i][j - 1];
代码:
1 class Solution { 2 public: 3 int minPathSum(vector<vector<int>>& grid) { 4 int dp[grid.size()][grid[0].size()]; 5 dp[0][0] = grid[0][0]; 6 for (int i = 1; i < grid.size(); ++i) { 7 dp[i][0] = dp[i - 1][0] + grid[i][0]; 8 } 9 for (int i = 1; i < grid[0].size(); ++i) { 10 dp[0][i] = dp[0][i - 1] + grid[0][i]; 11 } 12 for (int i = 1; i < grid.size(); ++i) { 13 for (int j = 1; j < grid[0].size(); ++j) { 14 dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; 15 } 16 } 17 return dp[grid.size() - 1][grid[0].size() - 1]; 18 } 19 };
以上是关于LeetCode64 Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章