https://leetcode-cn.com/problems/climbing-stairs/
爬楼梯问题假设你正在爬楼梯, 需要 n 阶你才能到达楼顶
每次你可以爬 1 或 2 个台阶, 你有多少种不同的方法可以爬到楼顶呢?
f(n)
种可能
假设先爬1阶, 剩下 n-1
阶有 f(n-1)
种可能
假设先爬2阶, 剩下 n-2
阶有 f(n-2)
种可能
因此爬n阶可以转化为两种爬n-1阶问题之和: f(n) = f(n-1) + f(n-2)
斐波那契公式
Fn=1/5[(1+52)n−(1−52)n] F_{n} = 1 / \sqrt{5} \left [ \left (\frac{1+\sqrt{5}}{2} \right)^{n} - \left (\frac{1-\sqrt{5}}{2} \right)^{n} \right ] Fn=1/5[(21+5)n−(21−5)n]
解方程后得到
Fn=1/5((1+52)n+1−(1−52)n+1) F_{n} = 1 / \sqrt{5} \left ( \left (\frac{1+\sqrt{5}}{2} \right)^{n+1} - \left (\frac{1-\sqrt{5}}{2} \right)^{n+1} \right ) Fn=1/5⎝⎛(21+5)n+1−(21−5)n+1⎠⎞
python
#动态规划
def climbStairs(n: int) -> int:
memory = {}
memory[1] = 1
memory[2] = 2
for i in range(3, n+1):
memory[i] = memory[i-1] + memory[i-2]
return memory[i]
#动态规划 (节省空间)
def climbStairs2(n: int) -> int:
temp1 = 1
temp2 = 2
temp = 0
for i in range(3, n+1):
temp = temp1 + temp2
temp1 = temp2
temp2 = temp
return temp
#斐波那契公式
def climbStairs3(n: int) -> int:
import math
sqrt5 = 5**0.5
fibn = math.pow((1+sqrt5)/2, n+1) - math.pow((1-sqrt5)/2, n+1)
return int(fibn/sqrt5)
step = climbStairs3(10)
print(step)
php
function climbStairs(int $n): int{
$memory = [];
$memory[1] = 1;
$memory[2] = 2;
for($i=3; $i<$n+1; $i++){
$memory[$i] = $memory[$i-1] + $memory[$i-2];
}
return $memory[$n];
}
function climbStairs2(int $n): int{
$temp = 0;
$temp1 = 1;
$temp2 = 2;
for($i=3; $i<$n+1; $i++){
$temp = $temp1 + $temp2;
$temp1 = $temp2;
$temp2 = $temp;
}
return $temp;
}
function climbStairs3(int $n): int{
$sqrt5 = sqrt(5);
$fibn = pow((1+$sqrt5)/2, $n+1) - pow((1-$sqrt5)/2, $n+1);
return (int)($fibn/$sqrt5);
}
$step = climbStairs3(10);
echo '';
echo $step;
作者:Gekkoou