Skip to content

Commit 05ff4b2

Browse files
authored
Merge pull request #819 from Chaedie/main
[Chaedie] Week 4
2 parents 5fa3676 + fa4a499 commit 05ff4b2

File tree

5 files changed

+237
-0
lines changed

5 files changed

+237
-0
lines changed

coin-change/Chaedie.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
직접 풀지 못해 알고달레 풀이를 참고했습니다. https://www.algodale.com/problems/coin-change/
3+
4+
Solution:
5+
1) BFS를 통해 모든 동전을 한번씩 넣어보며 amount와 같아지면 return
6+
7+
(c: coins의 종류 갯수, a: amount)
8+
Time: O(ca)
9+
Space: O(a)
10+
"""
11+
12+
13+
class Solution:
14+
def coinChange(self, coins: List[int], amount: int) -> int:
15+
q = deque([(0, 0)]) # (동전 갯수, 누적 금액)
16+
visited = set()
17+
18+
while q:
19+
count, total = q.popleft()
20+
if total == amount:
21+
return count
22+
if total in visited:
23+
continue
24+
visited.add(total)
25+
for coin in coins:
26+
if total + coin <= amount:
27+
q.append((count + 1, total + coin))
28+
return -1

merge-two-sorted-lists/Chaedie.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(
8+
self, list1: Optional[ListNode], list2: Optional[ListNode]
9+
) -> Optional[ListNode]:
10+
"""
11+
Solution:
12+
1) 리스트1 리스트2가 null 이 아닌 동안 list1, list2를 차례대로 줄세운다.
13+
2) list1이 남으면 node.next = list1로 남은 리스트를 연결한다.
14+
3) list2가 남으면 list2 를 연결한다.
15+
16+
Time: O(n)
17+
Space: O(1)
18+
"""
19+
dummy = ListNode()
20+
node = dummy
21+
22+
while list1 and list2:
23+
if list1.val < list2.val:
24+
node.next = list1
25+
list1 = list1.next
26+
else:
27+
node.next = list2
28+
list2 = list2.next
29+
node = node.next
30+
31+
if list1:
32+
node.next = list1
33+
elif list2:
34+
node.next = list2
35+
36+
return dummy.next

missing-number/Chaedie.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""
2+
Solution:
3+
1) 배열 정렬
4+
2) 0부터 for 문을 돌리는데 index 와 값이 다르면 return index
5+
3) 끝까지 일치한다면 return 배열의 크기
6+
Time: O(nlogn) = O(nlogn) + O(n)
7+
Space: O(1)
8+
"""
9+
10+
11+
class Solution:
12+
def missingNumber(self, nums: List[int]) -> int:
13+
nums.sort()
14+
for i in range(len(nums)):
15+
if i != nums[i]:
16+
return i
17+
return len(nums)

palindromic-substrings/Chaedie.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
Solution:
3+
1) 자신을 기준으로 l,r 포인터로 늘려주면서 같은 문자이면 palindrome
4+
이를 홀수, 짝수 글자에 대해 2번 진행해주면된다.
5+
Time: O(n^2) = O(n) * O(n/2 * 2)
6+
Space: O(1)
7+
8+
"""
9+
10+
11+
class Solution:
12+
def countSubstrings(self, s: str) -> int:
13+
result = 0
14+
for i in range(len(s)):
15+
l, r = i, i
16+
while l >= 0 and r < len(s):
17+
if s[l] != s[r]:
18+
break
19+
l -= 1
20+
r += 1
21+
result += 1
22+
23+
l, r = i, i + 1
24+
while l >= 0 and r < len(s):
25+
if s[l] != s[r]:
26+
break
27+
l -= 1
28+
r += 1
29+
result += 1
30+
return result

word-search/Chaedie.py

+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
"""
2+
Solution:
3+
1) board의 상하좌우를 탐색하되 아래 조건을 base case로 걸러준다.
4+
1.1) index 가 word의 길이이면 결과값 판단
5+
1.2) out of bounds 판단
6+
1.3) index를 통해 현재 글자와 board의 글자의 일치 판단
7+
1.4) 방문 여부 판단
8+
2) board를 돌면서 backtrack 이 True 인 케이스가 있으면 return True
9+
10+
m = row_len
11+
n = col_len
12+
L = 단어 길이
13+
Time: O(m n 4^L)
14+
Space: O(mn + L^2) = visit set O(mn) + 호출 스택 및 cur_word O(L^2)
15+
"""
16+
17+
18+
class Solution:
19+
def exist(self, board: List[List[str]], word: str) -> bool:
20+
ROWS, COLS = len(board), len(board[0])
21+
visit = set()
22+
23+
def backtrack(r, c, index, cur_word):
24+
if index == len(word):
25+
return word == cur_word
26+
if r < 0 or c < 0 or r == ROWS or c == COLS:
27+
return False
28+
if word[index] != board[r][c]:
29+
return False
30+
if (r, c) in visit:
31+
return False
32+
33+
visit.add((r, c))
34+
condition = (
35+
backtrack(r + 1, c, index + 1, cur_word + board[r][c])
36+
or backtrack(r - 1, c, index + 1, cur_word + board[r][c])
37+
or backtrack(r, c + 1, index + 1, cur_word + board[r][c])
38+
or backtrack(r, c - 1, index + 1, cur_word + board[r][c])
39+
)
40+
visit.remove((r, c))
41+
return condition
42+
43+
for i in range(ROWS):
44+
for j in range(COLS):
45+
if backtrack(i, j, 0, ""):
46+
return True
47+
return False
48+
49+
50+
"""
51+
Solution:
52+
공간 복잡도 낭비를 줄이기 위해 cur_word 제거
53+
Time: O(m n 4^L)
54+
Space: O(mn + L)
55+
"""
56+
57+
58+
class Solution:
59+
def exist(self, board: List[List[str]], word: str) -> bool:
60+
ROWS, COLS = len(board), len(board[0])
61+
visit = set()
62+
63+
def backtrack(r, c, index):
64+
if index == len(word):
65+
return True
66+
if r < 0 or c < 0 or r == ROWS or c == COLS:
67+
return False
68+
if word[index] != board[r][c]:
69+
return False
70+
if (r, c) in visit:
71+
return False
72+
73+
visit.add((r, c))
74+
condition = (
75+
backtrack(r + 1, c, index + 1)
76+
or backtrack(r - 1, c, index + 1)
77+
or backtrack(r, c + 1, index + 1)
78+
or backtrack(r, c - 1, index + 1)
79+
)
80+
visit.remove((r, c))
81+
return condition
82+
83+
for i in range(ROWS):
84+
for j in range(COLS):
85+
if backtrack(i, j, 0):
86+
return True
87+
return False
88+
89+
90+
"""
91+
Solution:
92+
공간 복잡도를 줄이기 위해 visit set 제거
93+
-> board[r][c]에 빈문자열을 잠깐 추가하는것으로 대체
94+
Time: O(m n 4^L)
95+
Space: O(L)
96+
"""
97+
98+
99+
class Solution:
100+
def exist(self, board: List[List[str]], word: str) -> bool:
101+
ROWS, COLS = len(board), len(board[0])
102+
103+
def backtrack(r, c, index):
104+
if index == len(word):
105+
return True
106+
if r < 0 or c < 0 or r == ROWS or c == COLS:
107+
return False
108+
if word[index] != board[r][c]:
109+
return False
110+
111+
temp = board[r][c]
112+
board[r][c] = ""
113+
condition = (
114+
backtrack(r + 1, c, index + 1)
115+
or backtrack(r - 1, c, index + 1)
116+
or backtrack(r, c + 1, index + 1)
117+
or backtrack(r, c - 1, index + 1)
118+
)
119+
board[r][c] = temp
120+
return condition
121+
122+
for i in range(ROWS):
123+
for j in range(COLS):
124+
if backtrack(i, j, 0):
125+
return True
126+
return False

0 commit comments

Comments
 (0)