Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions house-robber-ii/jamiebase.py
Comment thread
jamiebase marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
# Intuition
집이 원형으로 놓여있기 때문에 첫 번째 집을 터는 경우, 안 터는 경우일 때로 나누어 해를 구하고,
두 경우에서 최댓값 해를 구한다.

# Complexity
n은 nums의 길이라고 할 때,
- Time complexity: O(N)
- Space complexity: O(N)

"""


class Solution:
def rob(self, nums: list[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]

# 첫 번째 집을 터는 경우
dp1 = [0] * n
dp1[0] = dp1[1] = nums[0]
for i in range(2, n - 1):
dp1[i] = max(dp1[i - 2] + nums[i], dp1[i - 1])

# 첫 번째 집을 안 터는 경우
dp2 = [0] * n
dp2[1] = nums[1]
for j in range(2, n):
dp2[j] = max(dp2[j - 2] + nums[j], dp2[j - 1])

return max(max(dp1), max(dp2))
Comment thread
jamiebase marked this conversation as resolved.
28 changes: 28 additions & 0 deletions subtree-of-another-tree/jamiebase.py
Comment thread
jamiebase marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
# Approach
매 노드마다 같은 Tree인지 비교합니다.
Comment thread
jamiebase marked this conversation as resolved.

# Complexity
- Time complexity: 양 트리의 노드를 하나씩 다 비교해야 하므로 최악의 경우 O(N*M)
- Space complexity: root 트리 높이가 H라고 할 때 O(H)만큼 재귀 스택이 쌓임
"""


class Solution:
Comment thread
jamiebase marked this conversation as resolved.
def isSameTree(self, a, b):
if not a and not b:
return True
if not a or not b:
return False
if a.val != b.val:
return False
return self.isSameTree(a.left, b.left) and self.isSameTree(a.right, b.right)

def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not root:
return False

Comment thread
jamiebase marked this conversation as resolved.
if self.isSameTree(root, subRoot):
return True

return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
Loading