问题描述取自leetcode:https://leetcode.com/problems/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.
One Example:
Input: grid = [[1,3,1],
[1,5,1],
[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
我尝试在网格中设置一些负值,看起来转换函数仍然有效。
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
如果网格中存在负值,有人能拿出一个案例来证明DP对这个问题不起作用吗?
如果确实提到用户只能向下或向右移动,那么您的代码也完全适用于负数
但如果用户可以向任何方向移动,并且最终应该到达目的地,那么
以上代码仅适用于正元素考虑下面的示例
grid = [ [1 , 10000,-700,10],
[2 , 4 ,9 ,6 ] ]
在这种情况下,最小路径是1->2->4->9->-700->;9->6