diff --git a/house-robber-ii/jamiebase.py b/house-robber-ii/jamiebase.py new file mode 100644 index 0000000000..131e38d31f --- /dev/null +++ b/house-robber-ii/jamiebase.py @@ -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)) diff --git a/subtree-of-another-tree/jamiebase.py b/subtree-of-another-tree/jamiebase.py new file mode 100644 index 0000000000..6a764abc17 --- /dev/null +++ b/subtree-of-another-tree/jamiebase.py @@ -0,0 +1,28 @@ +""" +# Approach +매 노드마다 같은 Tree인지 비교합니다. + +# Complexity +- Time complexity: 양 트리의 노드를 하나씩 다 비교해야 하므로 최악의 경우 O(N*M) +- Space complexity: root 트리 높이가 H라고 할 때 O(H)만큼 재귀 스택이 쌓임 +""" + + +class Solution: + 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 + + if self.isSameTree(root, subRoot): + return True + + return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)