[Leetcode]Minimum Path Sum

来源:互联网 发布:在线监测数据造假刑法 编辑:程序博客网 时间:2024/06/05 22:58

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.


class Solution {public:    /*algorithm: 2D-DP    path(i,j) += min(path(i-1,j),path(i,j-1)) j > 0    path(i,j) += path(i-1,j) //j=0    example:    1 2    2 3    min path:1->2 : 3    time O(m*n) space O(m*n)    */    int minPathSum(vector<vector<int>>& grid) {        int m = grid.size();        int n = grid[0].size();        vector<vector<int> >dp(m,vector<int>(n,0));        dp[0][0] = grid[0][0];        for(int i = 1;i < n;i++)dp[0][i] = dp[0][i-1]+grid[0][i];        for(int i = 1;i < m;i++){            for(int j = 0;j < n;j++){                if(j == 0){                    dp[i][j] += dp[i-1][j] + grid[i][j];                }else{                    dp[i][j] += min(dp[i-1][j],dp[i][j-1]) + grid[i][j];                }            }        }                return dp[m-1][n-1];    }};

class Solution {public:    /*algorithm: 2D-DP    path(i,j) += min(path(i-1,j),path(i,j-1)) j > 0    path(i,j) += path(i-1,j) //j=0    example:    1 2    2 3    min path:1->2 : 3    resue grid space to optmize space usage to O(1)    time O(m*n) space O(1)    */    int minPathSum(vector<vector<int>>& grid) {        int m = grid.size();        int n = grid[0].size();        for(int i = 1;i < n;i++)grid[0][i] = grid[0][i-1]+grid[0][i];        for(int i = 1;i < m;i++){            for(int j = 0;j < n;j++){                if(j == 0){                    grid[i][j] += grid[i-1][j];                }else{                    grid[i][j] += min(grid[i-1][j],grid[i][j-1]);                }            }        }                return grid[m-1][n-1];    }};


0 0