This article is original, reprint please indicate the source Description of the story
You are are climbing a stair case. It takes n steps to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can your climb to the top?
Frog Jump step problem, a frog to jump on the N-storey high steps, one can jump a level, can also jump two, please ask this frog how many kinds of jump on this n-storey high step method. Thinking Analysis:
There are three ways to solve this problem, and here are three Python implementations of the method 1: Recursion
The frog jumps up the n step to have the F (N) method, divides these n kinds of methods into two kinds of classes, the first one of the last jump steps, such methods have a total of f (n-1) species, the second one of the last jump two steps, this method has a total of f (n-2), then the recursive formula F (n) =f (n-1) +f (n-2 ), obviously, F (1) =1,f (2) = 2, the recursive formula is as follows:
* This method is simple, but inefficient, exceeding the time limit *
The code is implemented as follows
Class Solution:
# @param {integer} n
# @return {integer}
def climbstairs (self, n):
if n==1: Return
1
elif n==2: return
2
else: return
self.climbstairs (n-1) +self.climbstairs (n-2)
Method 2: Use loops instead of recursion.
The principle of this method is still based on the formula above, but using loops instead of recursion, there is a greater increase in efficiency than the above code, you can AC
The code implementation is as follows:
Class Solution:
# @param {integer} n
# @return {integer}
def climbstairs (self, n):
if N==1 or n==2:
r Eturn n
a=1;b=2;c=3 for
i in range (3,n+1):
c=a+b;a=b;b=c return
C
method Three: Establish a simple mathematical model, using combinatorial number formula
I like this method better.
Set the frog jump on the N-level steps of a total of Z, which has X is a jump two, y times is a jump a level, then there are z=x+y, 2x+y=n, a fixed x, using a combination can be used to jump on the N-level steps of the method in common
Method of
And because X is in the interval [0,N/2], we just need to iterate through all the integers in this interval, and find out the sum of each x's corresponding combination to the final result.
The Python code is implemented as follows:
class Solution: # @param {integer} N # @return {integer} def climbstairs (self, N): def fact (N): Result=1 for I in Range (1,n+1): Result*=i return re Sult total=0 for I in Range (n/2+1): Total+=fact (i+n-2*i)/fact (i)/fact (n-2*i) return to Tal