64 Minimum Path Sum

less than 1 minute read

1. Dynamic Programing

// in place
int minPathSum(vector<vector<int>> &grid)
{
    for (int i = 0; i < grid.size(); i++)
    {
        for (int j = 0; j < grid[0].size(); j++)
        {
            if (i == 0 && j == 0)
            {
            }
            else
            {
                if (i == 0)
                {
                    grid[i][j] += grid[i][j - 1];
                }
                else if (j == 0)
                {
                    grid[i][j] += grid[i - 1][j];
                }
                else
                {
                    grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
                }
            }
        }
    }
    return grid.back().back();
}
Space Time
$O(1)$ $O(n^2)$

Leave a Comment