牛客网《剑指offer》之Python2.7实现:跳台阶

题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

思路一:

只有两种跳法:一级或两级,设有n个台阶,记n级台阶有f(n)种方法,那么要最后一次跳到n级,有两种方法,1级或2级,可知f(n) = f(n-1)+f(n-2),哇,有没有很眼熟???是的,它就是斐波那契数列的递推公式~

解法:

# -*- coding:utf-8 -*-
class Solution:
    def jumpFloor(self, number):
        # write code here
        res = [1, 1, 2, 3]
        while len(res) <= number:
            res.append(res[-1]+res[-2])
        return res[number]

思路二:

采用排列组合的思路:

猜你喜欢

转载自blog.csdn.net/ck_101/article/details/82728501