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;