"Fibonacci number" derivative title

First, the Fibonacci number

  Fibonacci numbers is a set of columns Number of columns: 1,1,2,3,5,8,13,21,34, ...... mathematically, the following is the Fibonacci sequence in a recursive method is defined : F (1) = 1, F (2) = 1, F (n) = F (n-1) + F (n-2) (n> = 3, n∈N *) that is greater than the portion 2 is obtained by adding by the first two.

  When the required value of the number N, we can also be solved by an iterative manner recursive

1, recursive

def fibonacci(n):
    if n == 1 or n == 2:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)

2, iterative

def fibonacci(n):
    dic = dict()
    dic[1] = 1
    dic[2] = 2
    for i in range(2, n+1):
        dic[i] = dic[i-1] + dic[i-2]
    return dic[n]

Second, the derivative title

 1, skip steps / stairs

 

  A frog can jump on a Class 1 level, you can also hop on level 2. The frog jumped seeking a total of n grade level how many jumps (the order of different calculation different results).

  Imagine we start counting from the topmost level, at the top level, can be used once completed, it may last only a step, it may be only two steps. Then remove the top-most one or two of these steps, and the rest, too, it has been the cycle continues, it is not the last to bottom? That is the way to continue to add up, similar to the Fibonacci number.

  Put it may be a bit chaotic, we verify by mathematical induction: a step, jump once; two steps, one can jump, jump can be divided into two bands, a total of two kinds; three steps, there are three ways; four steps there are five ...... see it that way is not that Fibonacci number. By then programmatically manner described above with reference to the code.

 2, skip steps II

  A frog can jump on a Class 1 level, you can also hop on level 2 ...... n It can also jump on stage. The frog jumped seeking a total of n grade level how many jumps.

  This question is a question to keep up with different conditions is that no one jumps much order.

  F(1) = 1

  F(2) = F(2-1) + F(2-2)         

  F(3) = F(3-1) + F(3-2) + F(3-3) 

  ...

  Wherein (nm) F m represents the number of order of n-th ordered a jump.

  F(n) = F(n-1) + F(n-2) + F(n-3) + ... + F(n-(n-1)) + F(n-n)   ①

  F(n-1) = F(n-2) + F(n-3) + ... + F(n-(n-1)) + F(n-n)      ②

  ① - ② obtained: F (n) = 2 x F (n-1)

  Thus code is as follows:

def jumpFloorII(number):
        # write code here
        if number == 0 or number == 1:
            return 1
        return jumpFloorII(number - 1) * 2

  As a note, written in general, laughed.

 

Guess you like

Origin www.cnblogs.com/lyuzt/p/11311893.html