Skip to content

Commit

Permalink
feat: Add Climbing Stairs
Browse files Browse the repository at this point in the history
  • Loading branch information
thispath98 committed Dec 18, 2024
1 parent 35e0c54 commit 0eb2ff9
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions climbing-stairs/thispath98.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
class Solution:
def climbStairsFact(self, n: int) -> int:
"""
Intuition:
1 + 1 + ... + 1 ๋Š” 2๊ฐ€ 0๊ฐœ์ผ ๋•Œ n์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ = 1.
1 + 2 + ... + 1 ๋Š” 2๊ฐ€ 1๊ฐœ์ผ ๋•Œ n์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ = (n-1)C1.
2 + 2 + ... + 1 ๋Š” 2๊ฐ€ 2๊ฐœ์ผ ๋•Œ n์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ = (n-2)C2.
...
์ฆ‰, n์ด 0๋ถ€ํ„ฐ ์ตœ๋Œ€๋กœ ๋†“์„ ์ˆ˜ ์žˆ๋Š” ๊ฐ’(two_cnt)๊นŒ์ง€
1๋กœ ๋†“์—ฌ์ ธ ์žˆ๋Š” ๋ฐฐ์—ด์—์„œ 2์˜ ์œ„์น˜๋ฅผ ์„ ํƒ(์กฐํ•ฉ)ํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™๋‹ค.
Time Complexity:
O(N^2 log N):
(n-i)Ci๋Š” O((N - i) log i)์ด๊ณ , i๊ฐ€ 0๋ถ€ํ„ฐ two_cnt๊นŒ์ง€ ์ฆ๊ฐ€ํ•  ๊ฒฝ์šฐ
๋Œ€๋žต O(N log N)๋กœ ๊ณ„์‚ฐํ•œ๋‹ค.
์ด๋ฅผ two_cnt(N//2) ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฏ€๋กœ, O(N^2 log N).
Space Complexity:
O(1):
answer๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด๊ฐ€๋ฉฐ ๊ฐ’ ๊ณ„์‚ฐ.
"""
import math

two_cnt = n // 2
answer = 1

for i in range(1, two_cnt + 1):
# (n - i)Ci
# ์—ฌ๊ธฐ์„œ int๋กœ ํ˜•๋ณ€ํ™˜ ํ•  ๊ฒฝ์šฐ ์ˆ˜์น˜์  ๋ถˆ์•ˆ์ • ๋ฐœ์ƒ
answer += math.factorial(n - i) / math.factorial(n - 2 * i) / math.factorial(i)

return int(answer) # int๋กœ ํ˜•๋ณ€ํ™˜ ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ TypeError

def climbStairsComb(self, n: int) -> int:
"""
Intuition:
`climbStairsFact`์—์„œ Factorial์€ ์ˆ˜์น˜์  ๋ถˆ์•ˆ์ •์„ฑ์œผ๋กœ ์ธํ•ด
๋”์šฑ ์•ˆ์ •์ ์ธ math.comb๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
Time Complexity:
O(N^2 log N):
(n-i)Ci๋Š” O((N - i) log i)์ด๊ณ , i๊ฐ€ 0๋ถ€ํ„ฐ two_cnt๊นŒ์ง€ ์ฆ๊ฐ€ํ•  ๊ฒฝ์šฐ
๋Œ€๋žต O(N log N)๋กœ ๊ณ„์‚ฐํ•œ๋‹ค.
์ด๋ฅผ two_cnt(N//2) ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฏ€๋กœ, O(N^2 log N).
Space Complexity:
O(1):
answer๋ฅผ ์—…๋ฐ์ดํŠธ ํ•ด๊ฐ€๋ฉฐ ๊ฐ’ ๊ณ„์‚ฐ.
"""
import math

two_cnt = n // 2
answer = 1

for i in range(1, two_cnt + 1):
# (n - i)Ci
# math.comb ๋ฉ”์†Œ๋“œ๋Š” ์ˆ˜์น˜์ ์œผ๋กœ ์•ˆ์ •์ ์œผ๋กœ ๊ณ„์‚ฐํ•ด์ค€๋‹ค
answer += math.comb(n - i, i)
return answer

def climbStairsFib(self, n: int) -> int:
"""
Intuition:
climb stairs ๋ฌธ์ œ๋Š” ๋Œ€ํ‘œ์ ์ธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด ๋ฌธ์ œ์ด๋‹ค.
์‹ค์ œ๋กœ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•ด๋ณด๋ฉด,
1 -> 1
2 -> 2
3 -> 3
4 -> 5
5 -> 8
...
๋กœ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์„ ๋”ฐ๋ฅด๋Š” ๊ฒƒ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.
Time Complexity:
O(N):
N๋ฒˆ ์ˆœํšŒํ•˜์—ฌ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด ๊ตฌํ˜„.
Space Complexity:
O(N):
N๊ฐœ ๋งŒํผ ํ•ด์‹œ key-value ์Œ์„ ์ €์žฅ.
"""
fib_dict = {1: 1, 2: 2, 3: 3}
for i in range(1, n + 1):
if i not in fib_dict:
fib_dict[i] = fib_dict[i - 1] + fib_dict[i - 2]
if i == n:
return fib_dict[i]

0 comments on commit 0eb2ff9

Please sign in to comment.