Skip to content

Commit cb01505

Browse files
committed
[:solved] # two problems
1 parent cec7a82 commit cb01505

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

coin-change/ppxyn1.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# idea: DFS/BFS, DP
2+
3+
from collections import deque
4+
class Solution:
5+
def coinChange(self, coins: List[int], amount: int) -> int:
6+
# Why Greedy is not possiple way?
7+
# A greedy is only optimal in specific coin systems (e.g., denominations like 1, 5, 10, 25)
8+
# For arbitrary coin denominations, a greedy approach does not always yield the optimal solution.
9+
queue = deque([(0,0)]) # (동전갯수, 누적금액)
10+
while queue:
11+
count, total = queue.popleft()
12+
if total == amount:
13+
return count
14+
for coin in coins:
15+
if total + coin <= amount:
16+
queue.append([count+1, total+ coin])
17+
return -1
18+
19+
# # BFS
20+
# def coinChange(self, coins: List[int], amount: int) -> int:
21+
# queue = deque([(0,0)]) # (동전갯수, 누적금액)
22+
# visited = set()
23+
# while queue:
24+
# count, total = queue.popleft()
25+
# if total == amount:
26+
# return count
27+
# if total in visited:
28+
# continue
29+
# visited.add(total)
30+
# for coin in coins:
31+
# if total + coin <= amount:
32+
# queue.append([count+1, total+ coin])
33+
# return -1
34+
35+
36+
# DP
37+
# dp[i] = min(dp[i], dp[i-coin]+1)
38+
# from collections import deque
39+
# class Solution:
40+
# def coinChange(self, coins: List[int], amount: int) -> int:
41+
# dp=[0]+[amount+1]*amount
42+
# for coin in coins:
43+
# for i in range(coin, amount+1):
44+
# dp[i] = min(dp[i], dp[i-coin]+1)
45+
# return dp[amount] if dp[amount] < amount else -1
46+
47+

word-search/ppxyn1.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# idea : dfs
2+
class Solution:
3+
def exist(self, board: List[List[str]], word: str) -> bool:
4+
ROWS, COLS = len(board), len(board[0])
5+
visited = [[False]*COLS for _ in range(ROWS)]
6+
7+
def dfs(r, c, index):
8+
if r < 0 or r >= ROWS or c < 0 or c >= COLS:
9+
return False
10+
if visited[r][c] or board[r][c] != word[index]:
11+
return False
12+
13+
if index == len(word) - 1:
14+
return True
15+
16+
visited[r][c] = True
17+
18+
found = (dfs(r+1, c, index+1) or
19+
dfs(r-1, c, index+1) or
20+
dfs(r, c+1, index+1) or
21+
dfs(r, c-1, index+1))
22+
23+
# For next backtracking
24+
visited[r][c] = False
25+
26+
return found
27+
28+
# Run DFS from every cell as a starting point
29+
for row in range(ROWS):
30+
for col in range(COLS):
31+
if dfs(row, col, 0):
32+
return True
33+
34+
return False
35+
36+
37+

0 commit comments

Comments
 (0)