一直青蛙可以调1个台阶或者一次跳2个台阶,一共N个台阶,有多少种跳法?
#!/usr/bin/env python #coding=utf-8 def qingwa(step): if step <= 0: raise Exception('error') if step == 1: return 1 if step == 2: return 2 return qingwa(step - 1) + qingwa(step - 2) def qingwa1(step): if step <= 0: raise Exception('error') if step == 1: return 1 if step == 2: return 2 list1 = [] list1.append(0) list1.append(1) list1.append(2) for i in range(3, step + 1): list1.append(list1[i - 1] + list1[i - 2]) return list1[-1] def qingwa2(step): if step <= 0: raise Exception('error') if step == 1: return 1 if step == 2: return 2 pre1 = 2 pre2 = 1 value = 0 for i in range(3, step + 1): value = pre1 + pre2 pre2 = pre1 pre1 = value return value if __name__ == '__main__': print(qingwa2(9)) print(qingwa(-1))