Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions coin-change/Chaewon-Park-STUDY.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 풀이1) 1차원 DP: dp[i] = i원을 만드는 최소 동전 수
# 시간 복잡도: O(금액 × 동전 종류 수), 공간 복잡도: O(금액)
class Solution:
def coinChange(self, coins, amount):
dp = [10**10 for _ in range(amount + 1)]
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins: #elem->coin으로 명시적으로 변경
if coin <= i: # 지금 동전을 낼 수 있는 경우
dp[i] = min(dp[i], dp[i - coin] + 1)
if dp[-1] == 10**10:
return -1
else:
return dp[-1]

43 changes: 43 additions & 0 deletions find-minimum-in-rotated-sorted-array/Chaewon-Park-STUDY.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# 찐막 풀이) 이진 탐색
# mid가 회전으로 앞에 온 큰 값 구간에 있으면 오른쪽 절반, 아니면 mid 포함 왼쪽 절반으로 좁힘
# Time: O(log n), Space: O(1)
class Solution:
def findMin(self, nums: list[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
if nums[left] < nums[right]: # 리뷰 피드백 후 수정 (구간이 이미 정렬돼 있으면 최솟값이 첫번째 원소이므로 즉시 반환)
return nums[left]
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]

# 풀이2) 투 포인터 방식 - right는 마지막 값에 고정하고 left만 이동
# 마지막 값보다 작아지는 첫 위치 = rotate지점 = 최솟값
# Time: O(n) (아직 O(log n) 조건은 만족 못 함)
# Space: O(1)
# class Solution:
# def findMin(self, nums: list[int]) -> int:
# left, right = 0, -1
# while nums[left] > nums[right]: # 처음으로 오름차순이 되기 전까지
# left += 1
# return nums[left]


# 풀이1) 정렬 후 원래 배열이 될 때까지 rotate
# Time: O(n^2) - 정렬 O(n log n) + 최대 n번 회전, 문제 조건 'You must write an algorithm that runs in O(log n) time.'에 위배
# Space: O(n)
# class Solution:
# def findMin(self, nums: list[int]) -> int:
# start = nums[0]
# nums.sort()
# trial = 0
# while nums[0] != start:
# end = nums.pop()
# nums.insert(0, end)
# trial += 1
# if nums[0] == start and trial != 0:
# break
# return nums[trial]
20 changes: 20 additions & 0 deletions maximum-depth-of-binary-tree/Chaewon-Park-STUDY.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right


# 재귀
# Time: O(n) - 모든 노드를 한 번씩 방문, Space: O(h) h(트리 높이)
class Solution:
def maxDepth(self, root: TreeNode | None) -> int:
def dfs(node):
if node is None:
return 0
left=dfs(node.left)
right=dfs(node.right)
return 1+max(left,right) # 자기 자신을 포함해야하므로 +1
return dfs(root)

47 changes: 47 additions & 0 deletions merge-two-sorted-lists/Chaewon-Park-STUDY.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

# 풀이2) answer 리스트 대신 노드 간 연결
# Time: O(m+n), Space: O(1) 공간복잡도를 줄일 수 있다는 것이 핵심
class Solution:
def mergeTwoLists(self, list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
dummy = ListNode() # 리뷰 피드백 후 수정 (initial -> dummy) 결과 리스트 앞에 두는 빈 노드, 고정
last = dummy # 리뷰 피드백 후 수정 (move -> last) 결과 리스트의 마지막 노드
while list1 and list2:
if list1.val <= list2.val:
last.next = list1 # list1 연결
list1 = list1.next # 그다음 노드로 넘어감
else:
last.next = list2 # list2 연결
list2 = list2.next
last = last.next # 결과의 마지막 노드로 이동
last.next = list1 or list2 # 남은 리스트를 통째로 연결
return dummy.next


# # 풀이1) (다른 풀이 더 고민 예정)
# # Time: O(n+m), Space: O(n+m) n: list1의 노드 개수, m: list2의 노드 개수
# class Solution:
# def mergeTwoLists(self, list1: ListNode | None, list2: ListNode | None) -> ListNode | None:
# answer = []
# while list1 and list2:
# if list1.val <= list2.val:
# answer.append(list1.val)
# list1 = list1.next # 그다음 노드로 넘어감
# else:
# answer.append(list2.val)
# list2 = list2.next
# while list1: # list1에 아직 원소가 남아있을 경우 전부 push
# answer.append(list1.val)
# list1 = list1.next
# while list2: # list2에 아직 원소가 남아있을 경우 전부 push
# answer.append(list2.val)
# list2 = list2.next
# head = None # 빈 리스트이면 None 반환 + 시작이 빈 list
# for elem in answer[::-1]:
# head = ListNode(elem, head)
# return head

65 changes: 65 additions & 0 deletions word-search/Chaewon-Park-STUDY.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#다른 풀이 이어서 고민할 것!

#2번째 (stack으로 DFS)
# Time: O(m * n * 3^L * L), Space: O(L^2) - L: word 길이
class Solution:
def exist(self, board: list[list[str]], word: str) -> bool:
dxs, dys = [1, 0, -1, 0], [0, 1, 0, -1]
m, n = len(board), len(board[0])

def in_range(x, y):
return 0 <= x < m and 0 <= y < n # 리뷰 피드백 후 수정 (비교 연산자 이어 쓰기)

for i in range(m):
for j in range(n):
if board[i][j] != word[0]:
continue
stack = []
stack.append((i, j, 0, {(i, j)})) # (x, y, word_idx, 지금 경로에서 지나온 칸들)
while stack:
x, y, word_idx, path = stack.pop() # 리뷰 피드백 후 수정 (index -> word_idx, board 좌표 i, j와 구분)
if word_idx == len(word) - 1:
return True
for k in range(4):
nx, ny = x + dxs[k], y + dys[k]
if in_range(nx, ny) and (nx, ny) not in path and board[nx][ny] == word[word_idx + 1]:
stack.append((nx, ny, word_idx + 1, path | {(nx, ny)})) # 갈림길마다 새 집합
return False





# 실패 로그

#반례:
#[["A","B","C","E"],["S","F","E","S"],["A","D","E","E"]]
#word="ABCESEEEFS"
# 오류 : 실패한 경로까지 visit에 들어가

# class Solution:
# def exist(self, board: list[list[str]], word: str) -> bool:
# dxs, dys = [1, 0, -1, 0], [0, 1, 0, -1]
# m, n = len(board), len(board[0])

# def in_range(x, y):
# return 0 <= x and x < m and 0 <= y and y < n

# for i in range(m):
# for j in range(n):
# if board[i][j] != word[0]:
# continue
# index = 0
# visit = set()
# stack = []
# stack.append((i, j, index))
# while stack:
# x, y, index = stack.pop()
# if index == len(word) - 1:
# return True
# visit.add((x, y))
# for k in range(4):
# nx, ny = x + dxs[k], y + dys[k]
# if in_range(nx, ny) and (nx, ny) not in visit and board[nx][ny] == word[index + 1]:
# stack.append((nx, ny, index + 1))
# return False
Loading