LeetCode 64. Minimum Path Sum
Description
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.
每个格子的数字表示经过它所需的消耗大小。寻找从左上到右下的最少路径消耗。
Solution
似曾相识
本题与《63. Unique Paths II》 使用相同的方法:
要到达右下角,需要经过左边或者上边的格子,而最少消耗自然是从这两个格子中选择到达它们所需消耗(非它们自身消耗)较少的一个:
$$ f(x, y) = cost_{(x,y)} + min(f(x-1, y), f(x, y-1)) $$
所以与之前一样,从左上开始往右下分别计算出每个格子的最少消耗,直到最终格子。
Code Here
|
|