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.
===============
思路:经典DP动态规划入门问题,
定义状态转移方程f[i][j] = min(f[i-1][j],f[i][j-1])+grid[i][j]
初始状态函数,二维数组f[][]的第一行和第一列
========
code 如下:
class Solution{ public: int minPathSum(vector<vector<int> > &grid){ if(grid.size()==0) return 0; const int m = grid.size(); const int n = grid[0].size(); int f[m][n]; f[0][0] = grid[0][0]; for(int i = 1;i<m;i++){ //初始化状态方程第一lie f[i][0] = f[i-1][0]+grid[i][0]; } for(int i = 1;i<n;i++){ //初始化状态方程第一hang f[0][i] = f[0][i-1]+grid[0][i]; } //运用状态方程求解 for(int i = 1;i<m;i++){ for(int j = 1;j<n;j++){ if(f[i-1][j]<f[i][j-1]){ cout<<i-1<<"-"<<j<<endl; }else{ cout<<i<<"-"<<j-1<<endl; } f[i][j] = min(f[i-1][j],f[i][j-1])+grid[i][j]; } } return f[m-1][n-1]; } };