|
| 1 | +class Solution: |
| 2 | + def climbStairsFact(self, n: int) -> int: |
| 3 | + """ |
| 4 | + Intuition: |
| 5 | + 1 + 1 + ... + 1 ๋ 2๊ฐ 0๊ฐ์ผ ๋ n์ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์ = 1. |
| 6 | + 1 + 2 + ... + 1 ๋ 2๊ฐ 1๊ฐ์ผ ๋ n์ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์ = (n-1)C1. |
| 7 | + 2 + 2 + ... + 1 ๋ 2๊ฐ 2๊ฐ์ผ ๋ n์ ๋ง๋ค ์ ์๋ ๊ฒฝ์ฐ์ ์ = (n-2)C2. |
| 8 | + ... |
| 9 | + ์ฆ, n์ด 0๋ถํฐ ์ต๋๋ก ๋์ ์ ์๋ ๊ฐ(two_cnt)๊น์ง |
| 10 | + 1๋ก ๋์ฌ์ ธ ์๋ ๋ฐฐ์ด์์ 2์ ์์น๋ฅผ ์ ํ(์กฐํฉ)ํ๋ ๊ฒ๊ณผ ๊ฐ๋ค. |
| 11 | +
|
| 12 | + Time Complexity: |
| 13 | + O(N^2 log N): |
| 14 | + (n-i)Ci๋ O((N - i) log i)์ด๊ณ , i๊ฐ 0๋ถํฐ two_cnt๊น์ง ์ฆ๊ฐํ ๊ฒฝ์ฐ |
| 15 | + ๋๋ต O(N log N)๋ก ๊ณ์ฐํ๋ค. |
| 16 | + ์ด๋ฅผ two_cnt(N//2) ๊น์ง ๋ฐ๋ณตํ๋ฏ๋ก, O(N^2 log N). |
| 17 | +
|
| 18 | + Space Complexity: |
| 19 | + O(1): |
| 20 | + answer๋ฅผ ์
๋ฐ์ดํธ ํด๊ฐ๋ฉฐ ๊ฐ ๊ณ์ฐ. |
| 21 | + """ |
| 22 | + import math |
| 23 | + |
| 24 | + two_cnt = n // 2 |
| 25 | + answer = 1 |
| 26 | + |
| 27 | + for i in range(1, two_cnt + 1): |
| 28 | + # (n - i)Ci |
| 29 | + # ์ฌ๊ธฐ์ int๋ก ํ๋ณํ ํ ๊ฒฝ์ฐ ์์น์ ๋ถ์์ ๋ฐ์ |
| 30 | + answer += math.factorial(n - i) / math.factorial(n - 2 * i) / math.factorial(i) |
| 31 | + |
| 32 | + return int(answer) # int๋ก ํ๋ณํ ํ์ง ์์ ๊ฒฝ์ฐ TypeError |
| 33 | + |
| 34 | + def climbStairsComb(self, n: int) -> int: |
| 35 | + """ |
| 36 | + Intuition: |
| 37 | + `climbStairsFact`์์ Factorial์ ์์น์ ๋ถ์์ ์ฑ์ผ๋ก ์ธํด |
| 38 | + ๋์ฑ ์์ ์ ์ธ math.comb๋ฅผ ์ฌ์ฉํ๋ค. |
| 39 | +
|
| 40 | + Time Complexity: |
| 41 | + O(N^2 log N): |
| 42 | + (n-i)Ci๋ O((N - i) log i)์ด๊ณ , i๊ฐ 0๋ถํฐ two_cnt๊น์ง ์ฆ๊ฐํ ๊ฒฝ์ฐ |
| 43 | + ๋๋ต O(N log N)๋ก ๊ณ์ฐํ๋ค. |
| 44 | + ์ด๋ฅผ two_cnt(N//2) ๊น์ง ๋ฐ๋ณตํ๋ฏ๋ก, O(N^2 log N). |
| 45 | +
|
| 46 | + Space Complexity: |
| 47 | + O(1): |
| 48 | + answer๋ฅผ ์
๋ฐ์ดํธ ํด๊ฐ๋ฉฐ ๊ฐ ๊ณ์ฐ. |
| 49 | + """ |
| 50 | + import math |
| 51 | + |
| 52 | + two_cnt = n // 2 |
| 53 | + answer = 1 |
| 54 | + |
| 55 | + for i in range(1, two_cnt + 1): |
| 56 | + # (n - i)Ci |
| 57 | + # math.comb ๋ฉ์๋๋ ์์น์ ์ผ๋ก ์์ ์ ์ผ๋ก ๊ณ์ฐํด์ค๋ค |
| 58 | + answer += math.comb(n - i, i) |
| 59 | + return answer |
| 60 | + |
| 61 | + def climbStairsFib(self, n: int) -> int: |
| 62 | + """ |
| 63 | + Intuition: |
| 64 | + climb stairs ๋ฌธ์ ๋ ๋ํ์ ์ธ ํผ๋ณด๋์น ์์ด ๋ฌธ์ ์ด๋ค. |
| 65 | + ์ค์ ๋ก ๊ฒฝ์ฐ์ ์๋ฅผ ๊ณ์ฐํด๋ณด๋ฉด, |
| 66 | + 1 -> 1 |
| 67 | + 2 -> 2 |
| 68 | + 3 -> 3 |
| 69 | + 4 -> 5 |
| 70 | + 5 -> 8 |
| 71 | + ... |
| 72 | + ๋ก ํผ๋ณด๋์น ์์ด์ ๋ฐ๋ฅด๋ ๊ฒ์ ์ ์ ์๋ค. |
| 73 | +
|
| 74 | + Time Complexity: |
| 75 | + O(N): |
| 76 | + N๋ฒ ์ํํ์ฌ ํผ๋ณด๋์น ์์ด ๊ตฌํ. |
| 77 | +
|
| 78 | + Space Complexity: |
| 79 | + O(N): |
| 80 | + N๊ฐ ๋งํผ ํด์ key-value ์์ ์ ์ฅ. |
| 81 | + """ |
| 82 | + fib_dict = {1: 1, 2: 2, 3: 3} |
| 83 | + for i in range(1, n + 1): |
| 84 | + if i not in fib_dict: |
| 85 | + fib_dict[i] = fib_dict[i - 1] + fib_dict[i - 2] |
| 86 | + if i == n: |
| 87 | + return fib_dict[i] |
0 commit comments