Python-剑指offer(7,8,9)斐波那契数列,跳台阶,变态跳台阶

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35164554/article/details/82557103

题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。

n<=39

环境:Python2.7.3

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        num = []
        num.append(0)
        num.append(1)
        num.append(1)
        for i in range(3,n+1):
            num.append(num[i-2]+num[i-1])
        return num[n]

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

思路:假设有10级台阶,最后一步的跳法智能为1或者2,所以当青蛙处在第九阶时一步即可(跳一阶),第八阶时也是一步即可(跳两阶),此时不要忽略第九阶中包含了第八阶先跳一阶的过程,所以第十级台阶的跳法是8,9的和,之后的计算过程看做是一个斐波那契数列即可。

# -*- coding:utf-8 -*-
class Solution:
    def jumpFloor(self, number):
        # write code here
        num = []
        num.append(0)
        num.append(1)
        num.append(2)
        for i in range(3,number+1):
            num.append(num[i-1]+num[i-2])
        return num[number]

题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

思路:和跳台阶的思想一样,不要忽略一步跳到的过程就好。

# -*- coding:utf-8 -*-
class Solution:
    def jumpFloorII(self, number):
        # write code here
        num = []
        n = number
        num.append(0)
        num.append(1)
        num.append(2)
        for i in range(3,n+1):
            count = 0
            for j in range(i):
                count = count+num[j]
            num.append(count+1)
            
        return num[n]

猜你喜欢

转载自blog.csdn.net/qq_35164554/article/details/82557103