C++ solution, beat 98.59%


  • 7
    W
    int minPathSum(vector<vector<int>>& grid) {
        if(grid.empty())
            return 0;
        
        vector<int> res(grid[0].size(),INT_MAX);
        res[0] = 0;
        
        for(int i=0;i<grid.size();i++)
            for(int j=0;j<grid[0].size();j++)
                if(j > 0)
                    res[j] = min(res[j-1],res[j]) + grid[i][j];
                else
                    res[j] = res[j] + grid[i][j];
        
        return res[grid[0].size()-1];
    }

  • 0
    G

    This solution is wrong. You have to initialize the res array the sum of its element, or else it will produce undefined values.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.