[Leetcode] 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 class Solution {

 2 public:

 3     int minPathSum(vector<vector<int> > &grid) {

 4         int m = grid.size();

 5         int n = grid[0].size();

 6         for (int i = 0; i < m; ++i) {

 7             for (int j = 0; j < n; ++j) {

 8                 if (i == 0 && j != 0) {

 9                     grid[i][j] += grid[i][j-1];

10                 } 

11                 if (i != 0 && j == 0) {

12                     grid[i][j] += grid[i-1][j];

13                 }

14                 if (i != 0 && j != 0) {

15                     grid[i][j] += min(grid[i-1][j], grid[i][j-1]);

16                 }

17             }   

18         }

19         return grid[m-1][n-1];

20     }

21 };

 

你可能感兴趣的:(LeetCode)