Skip to content

Commit 83ab2d0

Browse files
committed
Solution for Climbing Stairs #230
Add time and space complexity comments to climbStairs method
1 parent 8076816 commit 83ab2d0

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

climbing-stairs/dohyeon2.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

0 commit comments

Comments
 (0)