Skip to content

Commit 38d72c9

Browse files
Merge pull request #1628 from printjin-gmailcom/main
[printjin-gmailcom] Week 14 Solutions
2 parents eb472eb + d2bfffb commit 38d72c9

File tree

5 files changed

+73
-0
lines changed

5 files changed

+73
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def levelOrder(self, root):
3+
result = []
4+
def dfs(node, level):
5+
if not node:
6+
return
7+
if len(result) == level:
8+
result.append([])
9+
result[level].append(node.val)
10+
dfs(node.left, level + 1)
11+
dfs(node.right, level + 1)
12+
dfs(root, 0)
13+
return result

counting-bits/printjin-gmailcom.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class Solution:
2+
def countBits(self, n):
3+
ans = [0] * (n + 1)
4+
for i in range(1, n + 1):
5+
ans[i] = ans[i >> 1] + (i & 1)
6+
return ans

house-robber-ii/printjin-gmailcom.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class Solution:
2+
def rob(self, nums):
3+
if len(nums) == 1:
4+
return nums[0]
5+
def rob_linear(houses):
6+
prev = curr = 0
7+
for num in houses:
8+
prev, curr = curr, max(curr, prev + num)
9+
return curr
10+
return max(rob_linear(nums[:-1]), rob_linear(nums[1:]))

meeting-rooms-ii/printjin-gmailcom.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def minMeetingRooms(self, intervals):
3+
if not intervals:
4+
return 0
5+
starts = sorted(i[0] for i in intervals)
6+
ends = sorted(i[1] for i in intervals)
7+
s = e = rooms = 0
8+
while s < len(intervals):
9+
if starts[s] < ends[e]:
10+
rooms += 1
11+
else:
12+
e += 1
13+
s += 1
14+
return rooms

word-search-ii/printjin-gmailcom.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
3+
trie = {}
4+
for word in words:
5+
node = trie
6+
for char in word:
7+
node = node.setdefault(char, {})
8+
node["$"] = word
9+
rows, cols = len(board), len(board[0])
10+
result = []
11+
def dfs(r, c, node):
12+
char = board[r][c]
13+
if char not in node:
14+
return
15+
next_node = node[char]
16+
word = next_node.pop("$", None)
17+
if word:
18+
result.append(word)
19+
board[r][c] = "#"
20+
for dr, dc in [(-1,0),(1,0),(0,-1),(0,1)]:
21+
nr, nc = r + dr, c + dc
22+
if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
23+
dfs(nr, nc, next_node)
24+
board[r][c] = char
25+
if not next_node:
26+
node.pop(char)
27+
for r in range(rows):
28+
for c in range(cols):
29+
dfs(r, c, trie)
30+
return result

0 commit comments

Comments
 (0)