Created
October 4, 2012 06:12
-
-
Save hyfrey/3831736 to your computer and use it in GitHub Desktop.
leetcode Minimum Path Sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
*/ | |
class Solution { | |
public: | |
int minPathSum(vector<vector<int> > &grid) { | |
int N = grid.size(); | |
int M = grid[0].size(); | |
int scores[N][M]; | |
scores[N-1][M-1] = grid[N-1][M-1]; | |
for(int i = N-2; i >= 0; i--) { | |
scores[i][M-1] = grid[i][M-1] + scores[i+1][M-1]; | |
} | |
for(int j = M-2; j >= 0; j--) { | |
scores[N-1][j] = grid[N-1][j] + scores[N-1][j+1]; | |
} | |
for(int i = N-2; i >= 0; i--) { | |
for(int j = M-2; j >= 0; j--) { | |
scores[i][j] = grid[i][j] + min(scores[i+1][j], scores[i][j+1]); | |
} | |
} | |
return scores[0][0]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment