LeetCode064 Minimum Path Sum

详细见: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]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值