首页 > 代码库 > LeetCode:Minimum Path Sum
LeetCode: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.
思路:采用动态规划的方法,用数组存储起点到当前点距离的最小值。首先算出第一行和第一列的最小值,然后用公式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]; }
LeetCode:Minimum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。