Minimum Path Sum

原创 2017年01月02日 21:49:39

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.

public int minPathSum(int[][] grid) {

问题描述:

这个题目是”Unique Path”那道题的扩充,需要找到所有路径中,包含的元素之和最小的那(几)条路径的和。
所有元素都是非负数。

解法一:

思路:

这个问题考虑使用动态规划。

grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];

状态转移方程如上,但是有一行或者一列或者一个元素的情况,所有上述情况要考虑全面。

Code:

public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        for(int i = 0; i < m; i++){
            for(int j = 0;j < n; j++){
                if(i == 0 && j != 0){
                    grid[i][j] = grid[i][j] + grid[i][j - 1];
                }
                else if(i != 0 && j == 0){
                    grid[i][j] = grid[i][j] + grid[i - 1][j];
                }
                else if(i == 0 && j == 0){
                    grid[i][j] = grid[i][j];
                }
                else{
                    grid[i][j] = Math.min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
                }

            }
        }
        return grid[m-1][n-1];
    }
}

彩蛋:

很显然,上述代码的空间复杂度可以优化。。

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

动态规划--最小路径和(Minimum Path Sum)

原题   Given a m x n grid filled with non-negative numbers, find a path from top left to bottom rig...

Minimum Path Sum

题目名称 Minimum Path Sum—LeetCode链接描述 Given a m x n grid filled with non-negative numbers, find a pat...

LeetCode Minimum Path Sum

题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom ri...

Leetcode64 Minimum Path Sum

Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to...

leetcode[63] Minimum Path Sum 动态规划

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode刷题(C++)——Minimum Path Sum(Medium)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode 1.Minimum Path Sum 2.Unique Paths I and II

大家好,我是刘天昊,快到端午节了,今天说两道动态规划的题目(话说动规真的挺难的) 当然这三题是一样的解体思路先看Unique Paths  A robot is located a...

LeetCode: Minimum Path Sum [063]

【题目】 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom righ...

leetcode笔记:Minimum Path Sum

题目的大意是,给定一个m*n的网格,每个格子里有一个非负整数,找到一条从左上角到右下角的路径,使其经过的格子数值之和最小,每一步只能向右或向下走。可使用动态规划来解决该问题。

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...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)