64. Minimum Path Sum
Medium

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.
Python version:
class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m,n=len(grid),len(grid[0])
        dp = [[2147483647] * (n+1) for _ in range(m+1)]
        dp[1][1]=grid[0][0]
        for i in range(1,m+1):
            for j in range(1,n+1):
                if i==j==1:
                    continue
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1]
                #print(dp[-1][1])
        return dp[m][n]


solu=Solution()
myList2=[
    [1, 3, 1],
    [1, 5, 1],
    [4, 2, 1]
]
print(solu.minPathSum(myList2))

C++ version:

#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
// Author: Huahua
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m=grid.size(),n=grid[0].size();
        vector<vector<int>> dp= vector<vector<int>>(m + 1, vector<int>(n + 1, 2147483647));
        dp[1][1]=grid[0][0];
        for(int i=1;i<m+1;i++)
        {
            for(int j=1;j<n+1;j++)
            {
                if(i==j&&j==1)
                {
                    continue;
                }
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i-1][j-1];
            }

        }
        return dp[m][n];

    }
};
int main()
{
    Solution s;
    vector<vector<int>> grid=
    {
        {1,3,1},
        {1,5,1},
        {4,2,1}

    };
    int res=s.minPathSum(grid);
    cout<<res<<endl;
    return 0;
}

The difference is it want the min,so we initialize the array should use MAX_INT value 2147483647

We have to make dp larger than vector by +1,only in this way we can better solve the problem i-1 has minus one,if we want to initialize it to 0,it doesn't have matter for reason that it will be auto in 0,but we need it to be the MAX_INT we need the minimum value.So we have to use larger matrix but 63 needn't

70BONUS:

n is the input parameter

Two Attention Point:

1.because we initialize the 0-2 value so must let n+2 or the index may out of range.

2.dp[0] dp[1] this kinds of value need to initial by this way dp=[[0] for _ in range(N+2)]

3.first I let this position is 1000,but when I change into n+2 whole program quick a lot

4.range function can have two parameter (start,end) for i in range(3)---->0,1,2  for i in range(1,3)----->1,2

 

dp=[[0]  for _ in range(n+2)]
        dp[0] = 0
        dp[1] = 1
        dp[2] = 2

 

 

 



posted on 2019-08-07 00:26  黑暗尽头的超音速炬火  阅读(118)  评论(0编辑  收藏  举报