To solve the problem of finding the number of distinct ways to reach the nth step (taking 1 or 2 steps at a time), we can leverage a Fibonacci-like recurrence relation since each step depends on the previous two steps.
The key insight is:
n is the sum of the ways to reach step n-1 and step n-2. This leads to the recurrence relation:
f(n) = f(n-1) + f(n-2)
Base cases:
f(1) = 1 (only one way: take a single step) f(2) = 2 (two ways: 1+1 or directly 2 steps) The sequence generated is: 1,2,3,5,8,... which is the Fibonacci sequence shifted by one position (f(n) = Fib(n+1), where Fib(1)=1, Fib(2)=1).
This approach uses O(n) time and O(1) space (optimal for most cases):
def climb_stairs(n):
if n == 1:
return 1
elif n == 2:
return 2
a, b = 1, 2 # a = f(n-2), b = f(n-1)
for _ in range(3, n+1):
c = a + b
a = b
b = c
return b
n (1 or 2). n >=3, we maintain two variables (a and b) to store the number of ways to reach the previous two steps. We update these variables iteratively until we reach the nth step. Example:
For n=5:
a=1 (f(1)), b=2 (f(2)) n=3: c=1+2=3 → a=2, b=3 n=4: c=2+3=5 → a=3, b=5 n=5: c=3+5=8 → return b=8 For very large n (e.g., 1e18), use the fast doubling technique to compute Fibonacci numbers in logarithmic time:
def fib(n):
if n == 0:
return (0, 1)
a, b = fib(n >> 1) # n//2
c = a * (2*b - a)
d = a*a + b*b
if n & 1: # n is odd
return (d, c + d)
else:
return (c, d)
def climb_stairs_fast(n):
return fib(n)[1] # since f(n) = Fib(n+1) → fib(n+1)[0]? Wait let's confirm:
# Wait, let's adjust: if fib(n) returns (Fib(n), Fib(n+1)), then Fib(n+1) is the second element of fib(n).
# For f(1)=1=Fib(2) → fib(1) returns (Fib(1), Fib(2)) → (1, 2)? Let's see:
# Let's recheck: the fast doubling function here: let's take n=1:
# n=1 is odd, n>>1=0 → fib(0) returns (0, 1). Then c=0*(2*1 - 0)=0; d=02+12=1. Since n is odd, return (d, c+d) → (1,0+1=1). So Fib(1)=1, Fib(2)=1. Then f(n)= Fib(n+1). So f(1)= Fib(2)=1 → fib(1)[1] → yes (fib(1) returns (1, 1)). f(2)= Fib(3)=2 → fib(2) returns what? n=2 even: n>>1=1 → fib(1) returns (1, 1). c= 1*(2*1-1)=1*1=1; d= 1+1=2. So fib(2) returns (1,2). So Fib(3)=2 → which is fib(2)[1]. So yes: f(n)= fib(n)[1]. Because f(n)= Fib(n+1) → fib(n) gives (Fib(n), Fib(n+1)). So yes, climb_stairs_fast(n) = fib(n)[1].
n, use the fast doubling method to reduce time complexity to O(log n). Choose the method based on the constraints of your problem!
(免責聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點及立場。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責任歸材料提供方所有和承擔。本網(wǎng)站對此資訊文字、圖片等所有信息的真實性不作任何保證或承諾,亦不構(gòu)成任何購買、投資等建議,據(jù)此操作者風險自擔。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請聯(lián)系原著作權(quán)人,如有侵權(quán),請聯(lián)系本網(wǎng)進行刪除。