Skip to content

Commit c3f1add

Browse files
authored
Merge pull request #2071 from hongseoupyun/main
[hongseoupyun] Week 02 solutions
2 parents 983c956 + 0e1375d commit c3f1add

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

climbing-stairs/hongseoupyun.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
# This problem is a getting the number of cases to climb stairs just taking 1 or 2 steps at a time.
3+
# The pattern is similar to Fibonacci sequence.
4+
# As n increases by 1, the number of ways to climb will be 1, 2, 3, 5, 8, 13, 21
5+
# The Formula is to get number of ways to climb to the nth step is:
6+
# ways(n) = ways(n-1) + ways(n-2) with base of ways(1) = 1 and ways(2) = 2
7+
# which means the number of ways to climb is the sum of last two previous ways
8+
9+
10+
11+
# Time complexity is O(n) - loops n times
12+
# Space complexity is O(1) — memorizes only prev1 & prev2
13+
class Solution:
14+
def climbStairs(self, n: int) -> int:
15+
# Handling base case
16+
if n <= 1:
17+
return 1
18+
if n == 2:
19+
return 2
20+
21+
prev1 = 1
22+
prev2 = 2
23+
for i in range(n,n+1):
24+
current = prev2 + prev1
25+
prev1 = prev2
26+
prev2 = current
27+
28+
return prev2

climbing-stairs/hongseoupyun.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// # This problem is a getting the number of cases to climb stairs just taking 1 or 2 steps at a time.
2+
// # The pattern is similar to Fibonacci sequence.
3+
// # As n increases by 1, the number of ways to climb will be 1, 2, 3, 5, 8, 13, 21
4+
// # The Formula is to get number of ways to climb to the nth step is:
5+
// # ways(n) = ways(n-1) + ways(n-2) with base of ways(1) = 1 and ways(2) = 2
6+
// # which means the number of ways to climb is the sum of last two previous ways
7+
8+
9+
//Time complexity is O(n) - loops n times
10+
//Space complexity is O(1) — memorizes only prev1 & prev2
11+
function climbStairs(n: number): number {
12+
13+
14+
if (n <=1 ) return 1;
15+
if (n === 2) return 2;
16+
17+
// initial settiongs
18+
let prev1 = 1
19+
let prev2 = 2
20+
21+
//Loop from when the number of stairs is 3
22+
for (let i = 3; i<=n; i++){
23+
const current = prev2 + prev1
24+
//eg) when n = 3, prev1 = 1, prev2 = 2, current = 3 => prev1 = 2, prev2 = 3, return prev2
25+
//eg) when n = 4, prev1 = 2, prev2 = 3, current = 5 => prev1 = 3, preev2 = 5, return prev2
26+
prev1 = prev2
27+
prev2 = current
28+
}
29+
30+
return prev2
31+
};

0 commit comments

Comments
 (0)