详细见:leetcode.com/problems/minimum-path-sum
Java Solution: github
package leetcode;
public class P064_MinimumPathSum {
public static void main(String[] args) {
}
/*
* 写完就交,直接AC,好爽!!!
* 4 ms
* 51.74%
*/
static class Solution {
public int minPathSum(int[][] grid) {
int m = 0, n = 0;
if (grid == null || (m = grid.length) == 0 || (n = grid[0].length) == 0)
return 0;
for (int j = 1; j < n; j ++)
grid[0][j] += grid[0][j - 1];
for (int i = 1; i < m; i ++) {
grid[i][0] += grid[i - 1][0];
for (int j = 1; j < n; j ++)
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
return grid[m - 1][n - 1];
}
}
}
C Solution: github
/*
url: leetcode.com/problems/minimum-path-sum
AC 6ms 18.18%
*/
int _min(int a, int b) {
return a < b ? a : b;
}
int minPathSum(int** g, int rn, int cn) {
int* h = (int*) malloc(sizeof(int) * cn);
int i = 0, j = 0;
for (j = cn-1; j > -1; j --)
h[j] = (j==cn-1?0:h[j+1])+g[rn-1][j];
for (i = rn-2; i > -1; i --) {
h[cn-1] += g[i][cn-1];
for (j = cn-2; j > -1; j --) {
h[j] = _min(h[j], h[j+1]) + g[i][j];
}
}
i = h[0];
free(h);
return i;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/minimum-path-sum
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月14日
@details: Solution: 55ms 95.38%
'''
class Solution(object):
def minPathSum(self, g):
"""
:type g: List[List[int]]
:rtype: int
"""
if g == None or len(g) == 0: return 0
rn, cn = len(g), len(g[0])
h = [0] * cn
for j in range(cn-1, -1, -1):
h[j] = (0 if j == cn-1 else h[j+1])+g[rn-1][j]
for i in range(rn-2, -1, -1):
h[cn-1] += g[i][cn-1]
for j in range(cn-2, -1, -1):
h[j] = min(h[j], h[j+1]) + g[i][j]
return h[0]