题目描述:
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.
思路:采用动态规划的方法,用数组存储起点到当前点距离的最小值。首先算出第一行和第一列的最小值,然后用公式grid[i][j]=grid[i][j] + min(grid[i-1][j],grid[i][j-1])算出其余点的最小值,即可得结果。
代码:
int Solution::minPathSum(vector<vector<int> > &grid) { int m = grid.size(); int n = grid[0].size(); int i,j; for(i = 1;i < m;i++) grid[i][0] = grid[i-1][0] + grid[i][0]; for(j = 1;j < n;j++) grid[0][j] = grid[0][j-1] + grid[0][j]; for(i = 1;i < m;i++) for(j = 1;j < n;j++) grid[i][j] = grid[i][j] + min(grid[i-1][j],grid[i][j-1]); return grid[m-1][n-1]; }
原文地址:http://blog.csdn.net/yao_wust/article/details/42168279