64. Minimum Path Sum

2018/05/12 leetcode 共 747 字,约 3 分钟

Title

the problem link

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.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7

Explanation: Because the path 1→3→1→1→1 minimizes the sum.

Solution

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

                v[i][j]+=grid[i][j];
                cout<<v[i][j]<<" ";
            }
            cout<<endl;
        }
        return v[n-1][m-1];
    }
};

Search

    Table of Contents