有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶或3阶。实现一个算法,计算小孩有多少种上楼梯的方式。输入n,返回一个整数。
分析:
f(1) = '1'
f(2) = '11','2'
f(3) = '111','12','21','3'
f(4) 本身可以看作如下三种情况:
1. 走了1阶后再走3阶也就是f(1)+走3阶:===>'1'+'3' ==>'13' ==1种走法
f(1)=1
2. 走了2阶后再走2阶也就是f(2)+走2阶:===>'11'+'2','2'+'2' ==> '112','22' = 2种走法
f(2)=2
3. 走了3阶后再走1阶也就是f(3)+走1阶===>'111'+'1','12'+'1','21'+'1','3'+'1' ==>'1111','121','211','31'= 4种走法
f(3)=4
f(4) = '13','112','22','1111','121','211','31' =====> 7种走法=1 + 2+ 4=f(1)+f(2)+f(3) ---->递归取值
f(1)+f(2)+f(3)
即:f(n)=f(n-3)+f(n-2)+f(n-1)
#代码实现
>>> def func(n): ... if n==1: ... return 1 ... elif n==2: ... return 2 ... elif n==3: ... return 4 ... else: ... return func(n-1)+func(n-2)+func(n-3) #n>3时,用递归取值 ... >>> func(4) 7 >>> func(5) 13 >>> func(6) 24