Skip to content

Commit f069692

Browse files
authored
[parkhojeong] WEEK 14 Solutions (#2870)
* counting-bits solution * binary-tree-level-order-traversal solution * house-robber-ii solution * counting-bits solution * house-robber-ii solution * binary-tree-level-order-traversal solution
1 parent c954c97 commit f069692

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def levelOrder(self, root: TreeNode | None) -> list[list[int]]:
9+
if root is None:
10+
return []
11+
12+
deq = deque([root])
13+
14+
output = []
15+
while deq:
16+
nodes = []
17+
18+
for _ in range(len(deq)):
19+
node = deq.popleft()
20+
nodes.append(node.val)
21+
if node.left:
22+
deq.append(node.left)
23+
if node.right:
24+
deq.append(node.right)
25+
26+
output.append(nodes)
27+
28+
return output

‎counting-bits/parkhojeong.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def countBits(self, n: int) -> list[int]:
3+
if n == 0:
4+
return [0]
5+
6+
arr = [0, 1]
7+
def count(n: int) -> int:
8+
return arr[n // 2] + n % 2
9+
10+
for i in range(2, n + 1):
11+
arr.append(count(i))
12+
13+
return arr

‎house-robber-ii/parkhojeong.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def rob(self, nums: list[int]) -> int:
3+
if len(nums) == 1:
4+
return nums[0]
5+
6+
return max(
7+
max(self.rob_linear(nums[:-1])),
8+
max(self.rob_linear(nums[1:] ))
9+
)
10+
11+
def rob_linear(self, nums: list[int]):
12+
N = len(nums)
13+
14+
dp = [0] * (N + 1)
15+
dp[1] = nums[0]
16+
17+
for i in range(2, N + 1):
18+
dp[i] = max(dp[i - 2] + nums[i - 1], dp[i - 1])
19+
20+
21+
return dp

0 commit comments

Comments
 (0)