64. Minimum Path Sum 路径最小总和

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.

1. 我的答案 (动态规划,仍用一个辅助数组)(提交后发现竟然击败100%,哈哈,嘚瑟一下~)

class Solution {
public:
    int min(int a,int b){
        return a < b? a : b;
    }
    
    int minPathSum(vector<vector<int>>& grid) {
        int row = grid.size();
        int col = grid[0].size();
        if(row == 1 && col == 1)
        return grid[0][0];
        vector<int>vec(row,0);
        vec[0] = grid[0][0];
        for(int k = 1; k < row; k++)
            vec[k] = grid[k][0]+vec[k-1];
        for(int j = 1; j < col; j++)
        for(int i = 0; i < row; i++){
            if(i == 0)
                vec[i] += grid[i][j];
            else
                vec[i] = min(vec[i],vec[i-1])+grid[i][j];
        }
        return vec[row-1];
    }
};


你可能感兴趣的:(LeetCode,C++,dynamic,programming)