题目描述
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:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
我的解法
解题思路
如果做了#62和#63题的话这题就很简单了,同样还是只能往下和右走,不过不同的是每一点都有了一个代价,要找到一条代价最小的路径。第一列和第一行都只能从上一个点走过去,每个点的代价都等于自己的代价加上上一个点的路径代价。中间每点的状态转移方程如下:
$$ dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]$$
实现代码
1 | class Solution { |
Runtime: 8 ms, faster than 88.39% of C++ online submissions for Minimum Path Sum.
Memory Usage: 11.1 MB, less than 23.68% of C++ online submissions for Minimum Path Sum.