【第21期】观点:人工智能到底用 GPU?还是用 FPGA?

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];
    }
}

彩蛋:

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

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

相关文章推荐

64. Minimum Path Sum

题目:Minimum Path Sum原题链接:https://leetcode.com/problems/minimum-path-sum/ Given a m x n grid filled w...

Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from

[leet code] Minimum Path Sum

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

Minimum Path Sum -- LeetCode

原题链接:<a target="_blank" href="http://oj.leetcode.com/problems/minimum-path-sum/" style="text-decoration: none; color: rgb(33,135,187); font-family:
  • bcyy
  • bcyy
  • 2014-03-27 07:04
  • 29

leetcode 64. Minimum Path Sum

leetcode  64. Minimum Path Sum 终于有一个错误是因为符号优先级而存在的了 依然是dp,  要敢于尝试,很多问题并不难,而是因为我们畏难 ...

[LeetCode]64.Minimum Path Sum

【题目】 Given amxngrid filled with n

LeetCode --- 64. Minimum Path Sum

题目链接:Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top lef...

LeetCode Minimum Path Sum

Minimum Path Sum <span style="color: rgb(51,51,51); font-family: 'Helvetica
  • bcyy
  • bcyy
  • 2013-12-18 08:01
  • 38

LeetCode 64. Minimum Path Sum 解题报告

64. Minimum Path Sum My Submissions Question Total Accepted: 63385 Total Submissions: 185...

[LeetCode]64.Minimum Path Sum

【题目】 Given amxngrid filled with n
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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