码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]: 64: Minimum Path Sum

时间:2015-10-14 19:48:34      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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) {

        if(grid.length == 0){
            return 0;
        }
        
        int[][] intResult = new int[grid.length][grid[0].length];

        for(int i = 0;i<grid.length;i++){
            for(int j = 0;j<grid[i].length;j++){
                if(i==0 && j==0){
                    intResult[i][j] = grid[i][j];
                }else if(i == 0 && j!=0){
                    intResult[i][j] = intResult[i][j-1] + grid[i][j];
                }
                else if(j== 0 && i!= 0){
                    intResult[i][j] = intResult[i-1][j] + grid[i][j];
                }
                else{
                    int intX = intResult[i][j-1] + grid[i][j];
                    int intY = intResult[i-1][j] + grid[i][j];
                    
                    if(intX > intY){
                        intResult[i][j] = intY;
                    }
                    else{
                        intResult[i][j] = intX;
                    }
                }
            }
        }
        
        return intResult[grid.length-1][grid[0].length-1];
    }

 

[LeetCode]: 64: Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/savageclc26/p/4878166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!