Skip to content

Commit 41a97fa

Browse files
committed
solution of 70 climbing stairs
1 parent 0165731 commit 41a97fa

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @description 1์นธ ๋˜๋Š” 2์นธ์”ฉ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ์„ ๋•Œ n๋ฒˆ์งธ ๊ณ„๋‹จ์— ๋„๋‹ฌํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜
3+
* ์ ํ™”์‹: ways(n) = ways(n-1) + ways(n-2)
4+
* @param {number} n - ๊ณ„๋‹จ์˜ ์ด ๊ฐœ์ˆ˜
5+
* @returns {number} n๋ฒˆ์งธ ๊ณ„๋‹จ๊นŒ์ง€ ์˜ฌ๋ผ๊ฐ€๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์˜ ์ˆ˜
6+
*/
7+
function climbStairs(n: number): number {
8+
// base case
9+
// n์ด 1์ด๋ฉด 1๊ฐ€์ง€
10+
// n์ด 2์ด๋ฉด (1+1, 2) ์ด 2๊ฐ€์ง€
11+
if (n <= 2) return n;
12+
13+
// a = ways(n-2)
14+
// b = ways(n-1)
15+
let a = 1;
16+
let b = 2;
17+
18+
// 3๋ฒˆ์งธ ๊ณ„๋‹จ๋ถ€ํ„ฐ n๋ฒˆ์งธ ๊ณ„๋‹จ๊นŒ์ง€ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐ
19+
for (let i = 3; i <= n; i++) {
20+
// ํ˜„์žฌ ๊ณ„๋‹จ(i)์— ๋„๋‹ฌํ•˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜
21+
// = ๋ฐ”๋กœ ์ „ ๊ณ„๋‹จ(i-1) + ๋‘ ์นธ ์ „ ๊ณ„๋‹จ(i-2)
22+
const c = a + b;
23+
24+
// ๋‹ค์Œ ๊ณ„์‚ฐ์„ ์œ„ํ•ด ๊ฐ’ ์ด๋™
25+
// a โ† ์ด์ „ ways(i-1)
26+
// b โ† ํ˜„์žฌ ways(i)
27+
a = b;
28+
b = c;
29+
}
30+
31+
return b;
32+
}

0 commit comments

Comments
ย (0)