LeetCode 题解(48): Minimum Path Sum

来源:互联网 发布:centos u盘挂载 编辑:程序博客网 时间:2024/05/18 14:43

题目:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right whichminimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

题解:

动态规划,只需一个1xn的一维vector来保存中间值。

class Solution {public:    int minPathSum(vector<vector<int> > &grid) {        int m = grid.size();        int n = grid[0].size();        if(!m)            return -1;        vector<int> result(n);        result[0] = grid[0][0];        for(int i = 1; i < n; i++) {            result[i] = result[i-1] + grid[0][i];        }                for(int j = 1; j < m; j++) {            for(int k = 0; k < n; k++) {                if(!k)                    result[k] += grid[j][k];                else {                    result[k] = min(result[k-1], result[k]) + grid[j][k];                }            }        }                return result[n-1];    }};

Java版

public class Solution {    public int minPathSum(int[][] grid) {        if(grid.length == 0)            return -1;        int[] result = new int[grid[0].length];        result[0] = grid[0][0];        for(int i = 1; i < grid[0].length; i++) {            result[i] = result[i-1] + grid[0][i];        }                for(int j = 1; j < grid.length; j++) {            for(int k = 0; k < grid[j].length; k++) {                if(k == 0)                    result[k] += grid[j][k];                else {                    result[k] = Math.min(result[k-1], result[k]) + grid[j][k];                }            }        }                return result[grid[0].length-1];    }}

Python版

class Solution:    # @param grid, a list of lists of integers    # @return an integer    def minPathSum(self, grid):        if len(grid) == 0:            return -1        r = len(grid)        c = len(grid[0])        first = [grid[0][0]]        for i in range(1,c):            first.append(first[i-1] + grid[0][i])                for j in range(1, r):            for k in range(0, c):                if k == 0:                    first[k] = first[k] + grid[j][k]                else:                    first[k] = min(first[k-1], first[k]) + grid[j][k]                return first[c-1]


0 0