leetcode daily brush title plan --day61

Num 64 and minimum path

Because it is the first compulsory dynamic programming dynamic programming swipe tag

Over and over, to the vector problem is variable, here first with immutable array, a little bit of a waste possible?

Then you can find the minimum value plus the current value may come from two points.

A place that can be optimized: 1000 * 1000 is too large, in fact, you can use a one-dimensional array. (Be careful not to because of a one-dimensional array is omitted judge i, otherwise dp [j] iterative update to be wrong)

Commenting out the code is two-dimensional, some one-dimensional

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int x=grid.size();
        int y=grid[0].size();
        //int dp[1000][1000];
        int dp[1000];
        memset(dp,0,sizeof(dp));
        dp[0]=grid[0][0];
        /*for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(j>=1 && i>=1)
                    dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j];
                else if(j>=1)
                    dp[i][j]=dp[i][j-1]+grid[i][j];
                else if(i>=1)
                    dp[i][j]=dp[i-1][j]+grid[i][j];
            }
        }*/
        for(int i=0;i<x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(j>=1 && i>=1)
                    dp[j]=min(dp[j],dp[j-1])+grid[i][j];
                else if(j>=1)
                    dp[j]=dp[j-1]+grid[i][j];
                else if(i>=1)
                    dp[j]=dp[j]+grid[i][j];
            }
        }
        return dp[y-1];
    }
};
View Code

 

Guess you like

Origin www.cnblogs.com/tingxilin/p/11959461.html