Skip to content

Commit 8a74f65

Browse files
Merge pull request #1331 from printjin-gmailcom/main
[printjin-gmailcom] Week 4 Solutions
2 parents 0462985 + 783de6a commit 8a74f65

File tree

5 files changed

+74
-0
lines changed

5 files changed

+74
-0
lines changed

coin-change/printjin-gmailcom.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution:
2+
def coinChange(self, coins, amount):
3+
dp = [float('inf')] * (amount + 1)
4+
dp[0] = 0
5+
for coin in coins:
6+
for x in range(coin, amount + 1):
7+
dp[x] = min(dp[x], dp[x - coin] + 1)
8+
return dp[amount] if dp[amount] != float('inf') else -1
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from typing import List
2+
3+
class Solution:
4+
def findMin(self, nums):
5+
left, right = 0, len(nums) - 1
6+
while left < right:
7+
mid = (left + right) // 2
8+
if nums[mid] > nums[right]:
9+
left = mid + 1
10+
else:
11+
right = mid
12+
return nums[left]
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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+
8+
class Solution:
9+
def maxDepth(self, root: Optional[TreeNode]) -> int:
10+
if not root:
11+
return 0
12+
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class ListNode:
2+
def __init__(self, val=0, next=None):
3+
self.val = val
4+
self.next = next
5+
6+
class Solution:
7+
def mergeTwoLists(self, list1, list2):
8+
dummy = ListNode()
9+
current = dummy
10+
while list1 and list2:
11+
if list1.val < list2.val:
12+
current.next = list1
13+
list1 = list1.next
14+
else:
15+
current.next = list2
16+
list2 = list2.next
17+
current = current.next
18+
current.next = list1 if list1 else list2
19+
return dummy.next

word-search/printjin-gmailcom.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List
2+
3+
class Solution:
4+
def exist(self, board, word):
5+
m, n = len(board), len(board[0])
6+
def dfs(x, y, index):
7+
if index == len(word):
8+
return True
9+
if x < 0 or x >= m or y < 0 or y >= n or board[x][y] != word[index]:
10+
return False
11+
temp = board[x][y]
12+
board[x][y] = '#'
13+
found = (
14+
dfs(x + 1, y, index + 1) or dfs(x - 1, y, index + 1) or dfs(x, y + 1, index + 1) or dfs(x, y - 1, index + 1)
15+
)
16+
board[x][y] = temp
17+
return found
18+
19+
for i in range(m):
20+
for j in range(n):
21+
if dfs(i, j, 0):
22+
return True
23+
return False

0 commit comments

Comments
 (0)