LeetCode 64. Minimum Path Sum 解题报告

LeetCodeOJ 同时被 2 个专栏收录
34 篇文章 0 订阅

64. Minimum Path Sum

My Submissions
Total Accepted: 63385  Total Submissions: 185663  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    显然DP求解。

    我的AC代码

public class MinimumPathSum {

	public static void main(String[] args) {
		int[][] a = {{1,2},{1,1}};
		System.out.print(minPathSum(a));
	}

	public static int minPathSum(int[][] grid) {
		if (grid.length == 0 || grid[0].length == 0)
			return 0;

		// initiate
		int[][] dp = new int[grid.length][grid[0].length];
		dp[0][0] = grid[0][0];
		int rows = dp.length;
		int cols = dp[0].length;
		for (int i = 1; i < rows; i++) {
			dp[i][0] += (dp[i - 1][0] + grid[i][0]);
		}
		
		for (int i = 1; i < cols; i++) {
			dp[0][i] += (dp[0][i - 1] + grid[0][i]);
		}

		for (int i = 1; i < rows; i++) {
			for (int j = 1; j < dp[i].length; j++) {
				int min = Math.min(dp[i - 1][j], dp[i][j - 1]);
				dp[i][j] = grid[i][j] + min;
			}
		}
		
		return dp[rows -1][cols -1];
	}

}


  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值