[leetcode刷题系列]Minimum Path Sum

简单dp题,  练习了下滚动数组。


const int MAXN = 1e6 + 2;

int n, m;
int dp[2][MAXN];

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(grid.size() <= 0)
            return 0;
        n = grid.size();
        m = grid[0].size();
        int last = 0, now = 1;
        for(int i = 0; i < n; ++ i){
            now = 1 - last;
            for(int j = 0; j < m; ++ j){
                int in = -1;
                if(i - 1 >= 0)
                    if(in == -1 || dp[last][j] < in)
                        in = dp[last][j];
                if(j - 1 >= 0)
                    if(in == -1 || dp[now][j - 1] < in)
                        in = dp[now][j - 1];
                if(in == -1) in = 0;
                dp[now][j] = in + grid[i][j];
            }
            last = now;
        }
        return dp[last][m - 1];
    }
};


你可能感兴趣的:([leetcode刷题系列]Minimum Path Sum)