题意:有n级楼梯,你一次可以爬一级或两级,问爬上n级楼梯有多少种爬法。
分析: n 表示楼层 f(n) 表示 到达n层一共有多少种方法
n=1 f(1)=1 [1]
n=2 f(2)=2 [1 1] [2]
n=3 f(3)=3 [1 1 1] [1 2] [2 1]
n=4 f(4)=5 [1 1 1 1] [1 2 1] [2 1 1] [1 1 2] [2 2]
规律: f(n) = f(n-1) + f(n-2)
本质是斐波那契数列 递推式 dp[x] = dp[x-1] + dp[p-2]
实现:
C++版:
int climbStairs(int n)
{
if (n==1) return 1;
if (n==2) return 2;
int CSone = 1;
int CStwo = 2;
int CS = 0;
for(int k=2; k<=n; k++)
{
CS = CSone + CStwo;
CSone = CStwo;
CStwo = CS;
}
return CS;
}
Python版:
def climbStairs(n):
if n==1:
return 1
if n==2:
return 2
t = [1,1]
i = 2
if n >=2:
while i <= n:
t.append(t[i-1] + t[i-2])
i +=1
return t[-1]
reference:
python: https://blog.csdn.net/wxd_zswx/article/details/50188207