forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
49 lines (37 loc) · 1.05 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/// Source : https://leetcode.com/problems/minimum-path-sum/description/
/// Author : liuyubobobo
/// Time : 2017-11-21
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
/// Dynamic Programming
/// with O(n^2) space
///
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size();
assert(n > 0);
int m = grid[0].size();
assert(m > 0);
vector<vector<int>> res = grid;
for(int j = 1 ; j < m ; j ++)
res[0][j] += res[0][j-1];
for(int i = 1 ; i < n ; i ++)
res[i][0] += res[i-1][0];
for(int i = 1 ; i < n ; i ++)
for(int j = 1 ; j < m ; j ++)
res[i][j] += min(res[i-1][j], res[i][j-1]);
return res[n-1][m-1];
}
};
int main() {
vector<vector<int>> grid = {{1, 3, 1},
{1, 5, 1},
{4, 2, 1}};
cout << Solution().minPathSum(grid) << endl;
return 0;
}