Skip to content

Commit

Permalink
Merge pull request #819 from Chaedie/main
Browse files Browse the repository at this point in the history
[Chaedie] Week 4
  • Loading branch information
Chaedie authored Jan 3, 2025
2 parents 5fa3676 + fa4a499 commit 05ff4b2
Show file tree
Hide file tree
Showing 5 changed files with 237 additions and 0 deletions.
28 changes: 28 additions & 0 deletions coin-change/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
직접 풀지 못해 알고달레 풀이를 참고했습니다. https://www.algodale.com/problems/coin-change/
Solution:
1) BFS를 통해 모든 동전을 한번씩 넣어보며 amount와 같아지면 return
(c: coins의 종류 갯수, a: amount)
Time: O(ca)
Space: O(a)
"""


class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
q = deque([(0, 0)]) # (동전 갯수, 누적 금액)
visited = set()

while q:
count, total = q.popleft()
if total == amount:
return count
if total in visited:
continue
visited.add(total)
for coin in coins:
if total + coin <= amount:
q.append((count + 1, total + coin))
return -1
36 changes: 36 additions & 0 deletions merge-two-sorted-lists/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
"""
Solution:
1) 리스트1 리스트2가 null 이 아닌 동안 list1, list2를 차례대로 줄세운다.
2) list1이 남으면 node.next = list1로 남은 리스트를 연결한다.
3) list2가 남으면 list2 를 연결한다.
Time: O(n)
Space: O(1)
"""
dummy = ListNode()
node = dummy

while list1 and list2:
if list1.val < list2.val:
node.next = list1
list1 = list1.next
else:
node.next = list2
list2 = list2.next
node = node.next

if list1:
node.next = list1
elif list2:
node.next = list2

return dummy.next
17 changes: 17 additions & 0 deletions missing-number/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""
Solution:
1) 배열 정렬
2) 0부터 for 문을 돌리는데 index 와 값이 다르면 return index
3) 끝까지 일치한다면 return 배열의 크기
Time: O(nlogn) = O(nlogn) + O(n)
Space: O(1)
"""


class Solution:
def missingNumber(self, nums: List[int]) -> int:
nums.sort()
for i in range(len(nums)):
if i != nums[i]:
return i
return len(nums)
30 changes: 30 additions & 0 deletions palindromic-substrings/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""
Solution:
1) 자신을 기준으로 l,r 포인터로 늘려주면서 같은 문자이면 palindrome
이를 홀수, 짝수 글자에 대해 2번 진행해주면된다.
Time: O(n^2) = O(n) * O(n/2 * 2)
Space: O(1)
"""


class Solution:
def countSubstrings(self, s: str) -> int:
result = 0
for i in range(len(s)):
l, r = i, i
while l >= 0 and r < len(s):
if s[l] != s[r]:
break
l -= 1
r += 1
result += 1

l, r = i, i + 1
while l >= 0 and r < len(s):
if s[l] != s[r]:
break
l -= 1
r += 1
result += 1
return result
126 changes: 126 additions & 0 deletions word-search/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""
Solution:
1) board의 상하좌우를 탐색하되 아래 조건을 base case로 걸러준다.
1.1) index 가 word의 길이이면 결과값 판단
1.2) out of bounds 판단
1.3) index를 통해 현재 글자와 board의 글자의 일치 판단
1.4) 방문 여부 판단
2) board를 돌면서 backtrack 이 True 인 케이스가 있으면 return True
m = row_len
n = col_len
L = 단어 길이
Time: O(m n 4^L)
Space: O(mn + L^2) = visit set O(mn) + 호출 스택 및 cur_word O(L^2)
"""


class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROWS, COLS = len(board), len(board[0])
visit = set()

def backtrack(r, c, index, cur_word):
if index == len(word):
return word == cur_word
if r < 0 or c < 0 or r == ROWS or c == COLS:
return False
if word[index] != board[r][c]:
return False
if (r, c) in visit:
return False

visit.add((r, c))
condition = (
backtrack(r + 1, c, index + 1, cur_word + board[r][c])
or backtrack(r - 1, c, index + 1, cur_word + board[r][c])
or backtrack(r, c + 1, index + 1, cur_word + board[r][c])
or backtrack(r, c - 1, index + 1, cur_word + board[r][c])
)
visit.remove((r, c))
return condition

for i in range(ROWS):
for j in range(COLS):
if backtrack(i, j, 0, ""):
return True
return False


"""
Solution:
공간 복잡도 낭비를 줄이기 위해 cur_word 제거
Time: O(m n 4^L)
Space: O(mn + L)
"""


class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROWS, COLS = len(board), len(board[0])
visit = set()

def backtrack(r, c, index):
if index == len(word):
return True
if r < 0 or c < 0 or r == ROWS or c == COLS:
return False
if word[index] != board[r][c]:
return False
if (r, c) in visit:
return False

visit.add((r, c))
condition = (
backtrack(r + 1, c, index + 1)
or backtrack(r - 1, c, index + 1)
or backtrack(r, c + 1, index + 1)
or backtrack(r, c - 1, index + 1)
)
visit.remove((r, c))
return condition

for i in range(ROWS):
for j in range(COLS):
if backtrack(i, j, 0):
return True
return False


"""
Solution:
공간 복잡도를 줄이기 위해 visit set 제거
-> board[r][c]에 빈문자열을 잠깐 추가하는것으로 대체
Time: O(m n 4^L)
Space: O(L)
"""


class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
ROWS, COLS = len(board), len(board[0])

def backtrack(r, c, index):
if index == len(word):
return True
if r < 0 or c < 0 or r == ROWS or c == COLS:
return False
if word[index] != board[r][c]:
return False

temp = board[r][c]
board[r][c] = ""
condition = (
backtrack(r + 1, c, index + 1)
or backtrack(r - 1, c, index + 1)
or backtrack(r, c + 1, index + 1)
or backtrack(r, c - 1, index + 1)
)
board[r][c] = temp
return condition

for i in range(ROWS):
for j in range(COLS):
if backtrack(i, j, 0):
return True
return False

0 comments on commit 05ff4b2

Please sign in to comment.