-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1289. Minimum Falling Path Sum II
128 lines (84 loc) · 2.46 KB
/
1289. Minimum Falling Path Sum II
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
class Solution {
public int minFallingPathSum(int[][] grid)
{
int n = grid.length;
int[][] dp = new int[n][3];
for(int i = 0; i < n; i++)
{
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
for(int i = 0; i < n; i++)
{
int new_min = Math.min(dp[0][0], grid[0][i]);
if(new_min == grid[0][i])
{
dp[0][2] = i;
dp[0][1] = dp[0][0];
dp[0][0] = new_min;
}
else
{
dp[0][1] = Math.min(dp[0][1], grid[0][i]);
}
}
for(int i = 1; i < n; i++)
{
for(int j = 0; j < n; j++)
{
int new_min = Integer.MAX_VALUE;
if(j == dp[i-1][2])
{
new_min = dp[i-1][1] + grid[i][j];
}
else
{
new_min = dp[i-1][0] + grid[i][j];
}
if(new_min < dp[i][0])
{
dp[i][1] = dp[i][0];
dp[i][0] = new_min;
dp[i][2] = j;
}
else if(new_min < dp[i][1])
{
dp[i][1] = new_min;
}
}
}
return dp[n-1][0];
/*
Runtime 37 ms, Memory 52.14 MB
int n = grid.length, result = Integer.MAX_VALUE;
int[][] dp = new int[n][n];
for(int[] row : dp)
{
Arrays.fill(row, -1);
}
for(int i=0;i<n;i++)
{
dp[0][i] = grid[0][i];
}
for(int i=1; i<n; i++)
{
for(int j=0; j<n; j++)
{
int temp = Integer.MAX_VALUE;
for(int k = 0;k<n;k++)
{
if(j != k)
{
temp = Math.min(temp, grid[i][j] + dp[i-1][k]);
}
dp[i][j] = temp;
}
}
}
for(int i=0;i<n;i++)
{
result = Math.min(result, dp[n-1][i]);
}
return result;
*/
}
}