作者:disappearedgod
时间:2014-6-12
题目
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.
解法
DP解法
为了不麻烦还是多弄几个循环减少判断边界条件。
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
if(m==1 && n==1)
return grid[0][0];
for(int i = 1 ; i < m; i++)
grid[i][0] +=grid[i-1][0];
for(int j = 1; j < n ; j++)
grid[0][j] +=grid[0][j-1];
for(int i =1; i < m ; i++){
for(int j =1; j < n ; j++){
grid[i][j] += Math.min(grid[i][j-1], grid[i-1][j]);
}
}
return grid[m-1][n-1];
}
}
public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
if(m==1 && n==1)
return grid[0][0];
for(int i =0; i < m ; i++){
for(int j =0; j < n ; j++){
if(i==0 && j==0)
continue;
if(j==0){
grid[i][0] +=grid[i-1][0];
continue;
}
if(i==0){
grid[0][j] +=grid[0][j-1];
continue;
}
grid[i][j] += Math.min(grid[i][j-1], grid[i-1][j]);
}
}
return grid[m-1][n-1];
}
}
还是变快了
Submit Time | Status | Run Time | Language |
---|---|---|---|
0 minutes ago | Accepted | 388 ms | java |
1 minute ago | Accepted | 428 ms | java |