2019年10月18日 星期五

Minimum Path Sum


Minimum Path Sum

  • Lintcode : 110 / Leetcode : 64
  • Level : Easy

Problem

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.

Example
Example 1:
    Input:  [[1,3,1],[1,5,1],[4,2,1]]
    Output: 7

    Explanation:
    Path is: 1 -> 3 -> 1 -> 1 -> 1

Example 2:
    Input:  [[1,3,2]]
    Output: 6

    Explanation:  
    Path is: 1 -> 3 -> 2

Notice
You can only go right or down in the path..

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n * m)
space: O(1)

Answer

class Solution {
public:
    int minPathSum(vector<vector<int>> &grid) {
        if (grid.size() == 0 || grid[0].size() == 0) return 0;
        int m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 & j == 0) continue;
                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][j - 1], grid[i - 1][j]);
            }
        }
        return grid[m - 1][n - 1];
    }
};
tags: DP

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...