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
| 思路: 台阶cost = 前两个cost的的历史花费+cost的较小值
代码1: /** * @param Integer[] $cost * @return Integer */ function minCostClimbingStairs($cost) { $count = count($cost); // 范围到顶部 for ($i = 2; $i <= $count; $i++) { $cost[$i] += min($cost[$i - 1], $cost[$i - 2]); }
return array_pop($cost); }
代码2: /** * @param Integer[] $cost * * @return Integer */ function minCostClimbingStairs($cost) { $count = count($cost);
$curr = 0; $prev = 0; for ($i = 2; $i <= $count; $i++) { $next = min($curr + $cost[$i - 1], $prev + $cost[$i - 2]);
$prev = $curr; $curr = $next; }
return $curr; }
|