1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | class Triangle |
||
8 | { |
||
9 | public static function minimumTotal(array $triangle) |
||
10 | { |
||
11 | if (0 === $n = count($triangle)) { |
||
12 | return $n; |
||
13 | } |
||
14 | $dp = []; |
||
15 | for ($i = 0; $i < count($triangle[$n - 1]); $i++) { |
||
0 ignored issues
–
show
|
|||
16 | $dp[$i] = $triangle[$n - 1][$i]; |
||
17 | } |
||
18 | for ($i = $n - 2; $i >= 0; $i--) { |
||
19 | for ($j = 0; $j <= $i; $j++) { |
||
20 | $dp[$j] = min($dp[$j], $dp[$j + 1]) + $triangle[$i][$j]; |
||
21 | } |
||
22 | } |
||
23 | |||
24 | return $dp[0]; |
||
25 | } |
||
26 | |||
27 | public static function minimumTotal2(array $triangle) |
||
28 | { |
||
29 | if (0 === $n = count($triangle)) { |
||
30 | return $n; |
||
31 | } |
||
32 | |||
33 | $ans = $triangle[$n - 1]; |
||
34 | for ($i = $n - 2; $i >= 0; $i--) { |
||
35 | for ($j = 0; $j <= $i; $j++) { |
||
36 | $ans[$j] = $triangle[$i][$j] + min($ans[$j], $ans[$j + 1]); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | return $ans[0]; |
||
41 | } |
||
42 | } |
||
43 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: