原题链接:https://leetcode.com/problems/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.
样例:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
Solution: 题目意思很简单,找出从array[0][0] 到 array[m-1][n-1]的最优路径,使得路径的和最小。对于这个题,我们可以采用动态规划的思想,用sum[i][j]表示从array[0][0]走到array[i][j]的最小路径和,如果我们能计算出数组array中所有元素的sum[i][j]值,那么sum[m-1[[n-1]就是答案。
该动态规划的状态转移方程为:
当i=0且j=0时,sum[0][0] = array[0][0];
当i =0, j > 0时,sum[i][j] = array[i][j-1];
当i >0, j = 0时,sum[i][j] = array[i-1][j];
当i >0, j > 0时,sum[i][j] = array[i-1][j-1];
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int sum[m][n];
memset(sum, 0, sizeof(sum));
sum[0][0] = grid[0][0];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j != 0) sum[i][j] = sum[i][j-1] + grid[i][j];
else if (j == 0 && i != 0) sum[i][j] = sum[i-1][j] + grid[i][j];
else if (j > 0 && i > 0) sum[i][j] = min(sum[i][j-1] + grid[i][j], sum[i-1][j] + grid[i][j]);
}
}
return sum[m-1][n-1];
}
};
算法分析: 给定一个m x n的数组,状态数为O(m*n),每个状态迁移的复杂度为O(1),因而总复杂度为O(mn)。