We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 07dc7f0 commit a2572aeCopy full SHA for a2572ae
1 file changed
Week07/70-climbStairs.php
@@ -0,0 +1,29 @@
1
+<?php
2
+class Solution {
3
+
4
+ /**
5
+ * @param Integer $n
6
+ * @return Integer
7
+ */
8
+ function climbStairs($n) {
9
+ # 典型的斐波那契数列 f(n) = f(n-1)+f(n-2),使用DP
10
+ # 时间复杂度O(n),空间复杂度O(1)
11
+ if ($n<=2) {
12
+ return $n;
13
+ }
14
+ $i = 1;
15
+ $j = 2;
16
+ for ($k=3; $k<=$n; $k++) {
17
+ $num = $i + $j;
18
+ $i = $j;
19
+ $j = $num;
20
21
+ return $num;
22
23
+ # 使用递推数列的通项公式,f(n) = ( 1/ sqart(5) )[( (1+sqart(5))/2 )^n - ( (1-sqart(5) )/2 )^n]
24
+ # 时间复杂度O(logn),空间复杂度O(1)
25
+ $temp = sqrt(5);
26
+ $fibin = pow((1+$temp)/2, $n+1) - pow((1-$temp)/2, $n+1);
27
+ return (int)($fibin/$temp);
28
29
+}
0 commit comments