You is climbing a stair case. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In what many distinct ways can you climb to the top?
Test instructions: Climbing the stair problem. Each time you can climb one or two steps, ask a number of n steps, there are several ways to climb to the top.
Ideas:
N<=1, there is only one at this time.
N>1, for each step I, to reach the steps, the last step there are two ways, from i-1 step, or from i-2 two steps.
That is to say, the number of methods to reach step i = number of steps up to step I-1 + number of steps i-2. So the problem is a DP problem.
D (0) = 1
D (1) = 1
D (2) = d (2-1) + D (2-2)
D (3) = d (3-1) + D (3-2)
......
Well, the state transition equation is actually the Fibonacci sequence.
The code implementation gives you two options:
The Python code is as follows:
1 classsolution (object):2 defclimbstairs (self, n):3 """4 : Type N:int5 : Rtype:int6 """7 ifN<=1:8 return19res = []TenRes.append (1) OneRes.append (1) A forIinchRange (2,n+1): -Res.append (res[-1]+res[-2]) - returnRES[-1]
The Java code is as follows:
1 Public classSolution {2 Public intClimbstairs (intN) {3 if(n<=1)4 return1;5 6 intOnestep=1,twostep = 1,res = 0;7 8 for(inti = 2; I <= N; i++) {9res = OneStep +Twostep;TenTwostep =OneStep; OneOneStep =Res; A } - - returnRes; the } -}
Leetcode-70-climbing Stairs