猴子爬山一只顽猴在一座有N级台阶的小山上爬山跳跃。上山时需从山脚至山顶往上跳N级台阶,一步可跳1级,或跳3级,求上山有多少种不同的跳法? (N<50)
问题分析:
每一次都可以选择1,2,3有3种跳法
直接使用递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| jumpWay = [1, 3]
footstep = int(input())
jumping = 0
def jump(nowstep, footstep, jumpWay): if nowstep == footstep: global jumping jumping += 1 return elif nowstep > footstep: return else: for i in range(len(jumpWay)): jump(nowstep + jumpWay[i], footstep, jumpWay)
jump(0, footstep, jumpWay)
|
但是这种方式会提示 递归层数过多
想办法对算法进行合理优化,排列组合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| size = int(input()) n3 = size//3 res = 0
def jiecheng(n): num = 1 if n==1: return 1 else: for i in range(1,n+1): num*=i return num
def c43(n4,n3): return jiecheng(n4)//(jiecheng(n4-n3)*jiecheng(n3))
for i in range(size+1): for j in range(n3+1): if (i+j*3) == size: temp = j+i res+=c43(temp,j) print(res)
|