20150708 lintcode 总结 Minimum Path Sum
来源:互联网 发布:java数据库开发教程 编辑:程序博客网 时间:2024/06/13 22:24
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
- 20150708 lintcode 总结 Minimum Path Sum
- [Lintcode]Minimum Path Sum
- Minimum Path Sum--lintcode
- lintcode minimum-path-sum 最小路径和
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- leecode 解题总结:64. Minimum Path Sum
- LeetCode: Minimum Path Sum
- LeetCode Minimum Path Sum
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- Minimum Path Sum
- Minimum Path Sum
- [LeetCode] Minimum Path Sum
- [Leetcode] Minimum Path Sum
- Minimum Path Sum
- [LeetCode]Minimum Path Sum
- Minimum Path Sum
- Minimum Path Sum
- LibUSB-Win32程序介绍
- Hadoop学习视频电子书及相应心得
- android sqlite中判断某个表是否存在
- Java模式(适配器模式)
- 《猜猜看》游戏的开发总结
- 20150708 lintcode 总结 Minimum Path Sum
- 利用opencv绘制 灰度直方图 RGB直方图 HSV直方图 直方图均衡化
- eclipse参数配置
- 安卓屏幕适配方案
- nginx源码学习——Http连接对应的事件驱动模块
- C Language(1)
- html网页调用本地exe程序的实现方法
- Ubuntu下apt-get命令详解
- installShield使用