-
-
Notifications
You must be signed in to change notification settings - Fork 338
[liza0525] WEEK 02 solutions #2417
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
f2cc147
f8b31b0
1655639
5cff581
5cdf1e1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,3 +15,34 @@ def fibonacci(step): | |
| fibonacci(3) | ||
|
|
||
| return memo[n] | ||
|
|
||
|
|
||
| # 7기 풀이 | ||
| # 시간 복잡도: O(n) | ||
| # - memoization을 이용해 결과를 저장을 하면, 계산은 0 ~ n까지 한 번씩만 계산 | ||
| # - 즉, 계단의 개수 n이 최대 계산 횟수이므로 전체 연산은 O(n) | ||
| # 공간 복잡도: O(n) | ||
| # - memoization을 하기 위한 dict에 최대 n의 개수만큼만 저장 | ||
| # - 재귀 호출 스택 깊이도 최대 n | ||
| class Solution: | ||
| # 해당 문제는 이전 계단까지 계산된 경우의 수를 찾아가며 현재 계단까지 오를 수 있는 경우의 수를 계산한다. | ||
| # n번째 계단까지 오를 수 있는 경우의 수는 (n-1번째까지 오를 수 있는 경우의 수) + (n-2번째까지 오를 수 있는 경우의 수)이다. | ||
| # 이는 동적 프로그래밍을 이용해 memoization을 하며 풀 수 있는 문제라고 할 수 있다. | ||
| def climbStairs(self, n: int) -> int: | ||
| memo = {} | ||
|
|
||
| def dfs(n): | ||
| # n이 0 또는 1일 경우에는 하나의 방법만 있기 때문에 memo에 1을 넣고 return해준다. | ||
| if n <= 1: | ||
| memo[n] = 1 | ||
| return memo[n] | ||
|
|
||
| # memoization을 이미한 경우에는 memo에서 결과를 꺼내 return해준다. | ||
| if n in memo: | ||
| return memo[n] | ||
|
|
||
| # (n번째까지 오를 수 있는 경우의 수) = (n-1번째까지 오를 수 있는 경우의 수) + (n-2번째까지 오를 수 있는 경우의 수) | ||
| memo[n] = dfs(n - 1) + dfs(n - 2) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 저는 a,b,c로 지정해서 풀었는데 이렇게 함수로 만들어서 푸니까 더 직관적이네요!
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 우와 어떻게 푸셨는지 궁금해서 구경하고 왔는데, 제겐 새로운 풀이 방법이었습니다! |
||
| return memo[n] | ||
|
|
||
| return dfs(n) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
덕분에 memoization에 대해서도 리뷰했습니다!