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 1:
1 | [[1,3,1], |
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
动态规划问题,先确定状态转移方程,dp[i][j]表示到下标为i,j的位置时的最优解
1 | dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j] |
初值
1 | dp[0][0] = grid[0][0] |
时间复杂度O(mn),空间复杂度O(mn),可以通过滚动数组优化把空间复杂度降维到O(n)
1 | class Solution { |