-
-
Notifications
You must be signed in to change notification settings - Fork 245
[mangodm-web] Week14 Solutions #600
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
from collections import deque | ||
from typing import List, Optional | ||
|
||
|
||
class TreeNode: | ||
def __init__(self, val=0, left=None, right=None): | ||
self.val = val | ||
self.left = left | ||
self.right = right | ||
|
||
|
||
class Solution: | ||
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: | ||
""" | ||
- Idea: 너비 우선 탐색(BFS)를 이용하여 이진 트리를 단계 별로 순회한다. | ||
- Time Complexity: O(n). n은 트리의 노드 수. | ||
모든 노드를 한번씩 방문하므로 O(n) 시간이 걸린다. | ||
- Space Complexity: O(n). n은 트리의 노드 수. | ||
가장 아래 단계에 있는 노드를 저장할 때 가장 많은 메모리를 사용하고, 이는 n에 비례하기 때문에 O(n) 만큼의 메모리가 필요하다. | ||
""" | ||
if not root: | ||
return [] | ||
|
||
result = [] | ||
queue = deque() | ||
queue.append(root) | ||
|
||
while queue: | ||
level = [] | ||
|
||
for i in range(len(queue)): | ||
node = queue.popleft() | ||
level.append(node.val) | ||
|
||
if node.left: | ||
queue.append(node.left) | ||
if node.right: | ||
queue.append(node.right) | ||
|
||
result.append(level) | ||
|
||
return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from typing import List | ||
|
||
|
||
class Solution: | ||
def rob(self, nums: List[int]) -> int: | ||
""" | ||
- Idea: i번째 집까지의 최대 금액은 두 가지 중 더 큰 값으로 결정된다. | ||
1. (i-2번째 집까지의 최대 금액) + i번째 집의 금액 | ||
2. (i-1번째 집까지의 최대 금액) | ||
이를 이용해 동적 프로그래밍으로 각 집까지의 최대 금액을 계산한다. | ||
|
||
다만, 맨 마지막 집과 첫번째 집이 이어진 사이클(cycle) 형태이기 때문에 | ||
첫번째 집과 마지막 집이 동시에 도둑맞을 수는 없다. | ||
이를 처리하기 위해 두 가지 경우로 나눠서 각각 계산하고, 둘 중 더 큰 값을 선택한다. | ||
1. 첫번째 집을 포함하고 마지막 집을 포함하지 않는 경우 | ||
2. 첫번째 집을 포함하지 않고 마지막 집을 포함하는 경우 | ||
- Time Complexity: O(n). n은 집의 개수. | ||
모든 집을 한번씩 순회해야 하므로 O(n) 시간이 걸린다. | ||
- Space Complexity: O(n). n은 집의 개수. | ||
각 집까지의 최대 금액을 저장하기 위해 배열을 사용하므로 O(n) 만큼의 메모리가 필요하다. | ||
""" | ||
if len(nums) == 1: | ||
return nums[0] | ||
|
||
dp1 = [0] + [0] * len(nums) | ||
dp1[1] = nums[0] | ||
|
||
dp2 = [0] + [0] * len(nums) | ||
dp2[1] = 0 | ||
|
||
for i in range(2, len(nums) + 1): | ||
dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i - 1]) | ||
dp2[i] = max(dp2[i - 1], dp2[i - 2] + nums[i - 1]) | ||
|
||
return max(dp1[-2], dp2[-1]) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
공간복잡도 O(1)으로 최적화가 가능할 것 같습니다!
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.
그렇군요. 좀 더 고민해봐야겠네요. 코멘트 주셔서 감사합니다! 😄