class Fib { //自底向上计算结果 public function solution($N) { $current = 0; $next = 1; while ($N-- > 0) { $next = $next + $current; $current = $next - $current; } return (int)$current; } } $fib = new Fib(); $res = $fib->solution(10);
算法使用了自底向上的方法,通过迭代计算斐波那契数子问题的结果,最后获得最终结果。
复杂度分析:
- 时间复杂度:O(N)O(N)。
- 空间复杂度:O(N)O(N),使用了空间大小为N 的数组。
Visits: 399