File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ // TC: O(n)
3+ // SC: O(1)
4+ public int climbStairs (int n ) {
5+ if (n < 3 ) {
6+ // If n is less than 3 there are n ways.
7+ return n ;
8+ }
9+
10+ // There is one way to reach the first stair.
11+ int nMinus2 = 1 ;
12+ // There are two ways to reach the second stair.
13+ int nMinus1 = 2 ;
14+
15+ int nZero = nMinus1 + nMinus2 ;
16+
17+ for (int step = 3 ; step <= n ; step ++) {
18+ // To reach the third stair, it must come from the first stair or the second
19+ // stair.
20+ // The number of ways to reach the nth stair is the sum of those of the (n-1)th
21+ // stair and those of the (n-2)th stair.
22+ nZero = nMinus1 + nMinus2 ;
23+
24+ nMinus2 = nMinus1 ;
25+ nMinus1 = nZero ;
26+ }
27+
28+ // A separate variable name is used to distinguish between nZero and nMinus1 so
29+ // that the nth value is explicit
30+ return nZero ;
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments