关闭

20150708 lintcode 总结 Minimum Path Sum

标签: lintcode
227人阅读 评论(0) 收藏 举报
分类:

Easy Minimum Path Sum

34%
Accepted

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. You can only move either down or right at any point in time.

虽然是简单的题,感觉也不简单

Time complexity: O(m*n); Space complexity: O(m*n)

public class Solution {
    /**
     * @param grid: a list of lists of integers.
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] grid) {
        // write your code here
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int[][] temp = new int[m][n];
        
        for(int i = 0; i<m ; i++){      	
        	for(int j = 0; j<n; j++){
        		if(i==0 && j==0){
        			temp[0][0] = grid[0][0];
        		}else if(i==0){
            		temp[0][j] = temp[0][j-1] + grid[i][j];
            	}else if(j==0){
            		temp[i][0] = temp[i-1][0] + grid[i][j];
            	}else{
            	    temp[i][j] = Math.min(temp[i-1][j], temp[i][j-1]) + grid[i][j];
            	}      		
    	   }
       }
        
<span style="white-space:pre">	</span>return temp[m-1][n-1];
    }
}

方法2:time complexity: O(m*n); space complexity: O(n)

public class Solution {
    /**
     * @param grid: a list of lists of integers.
     * @return: An integer, minimizes the sum of all numbers along its path
     */
    public int minPathSum(int[][] grid) {
        // write your code here
    	if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }
    	int m = grid.length;
        int n = grid[0].length;
        int[] temp = new int[n];
        
        for(int i = 0; i<m; i++){     
        	for(int j = 0; j<n; j++){
        		if(i == 0 && j == 0 ){
        			temp[0] = grid[0][0];
        		}else if(i == 0 ){
        			temp[j] = temp[j-1] + grid[0][j];
        		}else if(j == 0 ){
        			temp[0] = temp[0] + grid[i][0];
        		}else{
        			temp[j] = Math.min(temp[j], temp[j-1]) + grid[i][j];
        		}	
        	}       		
       }      
        return temp[n-1];
    }
}


0
0

猜你在找
【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐(算法+实战)--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4249次
    • 积分:166
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类