https://leetcode-cn.com/problems/climbing-stairs/
爬楼梯问题
假设你正在爬楼梯, 需要 n 阶你才能到达楼顶
每次你可以爬 1 或 2 个台阶, 你有多少种不同的方法可以爬到楼顶呢?
- 设爬 n 个台阶有
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)
斐波那契公式
解方程后得到
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 '<pre>';
echo $step;