We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent b6c6b31 commit 40f3ee9Copy full SHA for 40f3ee9
MinimumPathSum/MinimumPathSum.cpp
@@ -22,4 +22,32 @@ class Solution {
22
}
23
return dp[m-1][n-1];
24
25
-};
+};
26
+
27
+// O(n) space
28
+class Solution {
29
+public:
30
+ int minPathSum(vector<vector<int> > &grid) {
31
+ if (grid.empty()) {
32
+ return 0;
33
+ }
34
+ int m = grid.size();
35
+ int n = grid[0].size();
36
+ vector<vector<int>> dp(2, vector<int>(n, 0));
37
+ int T1 = 1;
38
+ int T2 = 0;
39
+ for (int i = 0; i < m; i++) {
40
+ T1 ^= 1;
41
+ T2 ^= 1;
42
+ dp[T2][0] = dp[T1][0] + grid[i][0];
43
+ for (int j = 1; j < n; j++) {
44
+ if (i == 0) {
45
+ dp[T2][j] = dp[T2][j-1] + grid[i][j];
46
+ } else {
47
+ dp[T2][j] = grid[i][j] + min(dp[T1][j], dp[T2][j-1]);
48
49
50
51
+ return dp[T2][n-1];
52
53
0 commit comments