20150708 lintcode 总结 Minimum Path Sum
2015-07-08 15:09
148 查看
Easy Minimum
Path Sum
Show result
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]
;
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
;
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];
}
}
相关文章推荐
- 20150708 lintcode 总结 Binary Search Tree Iterator
- 20150707 lintcode 总结 Search Range in Binary Search Tree
- 20150624 lintcode 总结 binary-tree-level-order-traversal **
- 20150624 lintcode 总结 Lowest Common Ancestor
- 20150624 lintcode 总结 Balanced Binary Tree
- Lintcode(1)-两个字符串是变位词
- Lintcode(2)-比较字符串
- Lintcode(3)-字符串查找
- Lintcode(4)-乱序字符串
- Lintcode(5)-最长公共子串
- Lintcode(6)-最长公共前缀
- Lintcode(7)-删除元素
- #LintCode# Binary Search
- Nth to Last Node in List
- Partition List
- LintCode刷题之路(一)
- 爬楼梯
- LintCode刷题链表排序——归并和快速排序
- 克隆二叉树
- 旋转图像