Repository navigation
[Chaewon-Park-STUDY] WEEK 04 Solutions #2966
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Chaewon-Park-STUDY
wants to merge
15
commits into
DaleStudy:main
Choose a base branch
from
Chaewon-Park-STUDY:week4
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+228
−0
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
c569559
Create Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 2f71323
Create Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 53b6f2c
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 2df0d14
Create Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 410ff56
Create Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 7a1aad2
Create Chaewon-Park-STUDY.py
Chaewon-Park-STUDY c99a0b4
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 82cf1fa
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY f5b20e4
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY e9e7d3b
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 569d860
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 73d00c5
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 731729f
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY 5685ef5
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY d19d86f
Update Chaewon-Park-STUDY.py
Chaewon-Park-STUDY File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
43
find-minimum-in-rotated-sorted-array/Chaewon-Park-STUDY.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 # 남은 리스트를 통째로 연결 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 삼항연산자보다 list1 or list2 로 하면 더 간결하네요. 참고하겠습니다.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 저도 None 다루는 게 아직 완전 익숙하지는 않은데, 요즘 최대한 간결하게 써보려고 이렇게 하고 있습니다! |
||
| 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 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| #3번째 (stack으로 DFS) - 리뷰 피드백 후 수정 (경로마다 path를 복사하는 대신 board에 '*'로 방문 표시 후 복구) | ||
| #리뷰 피드백 이후 수정 풀이 | ||
| # 전반적인 풀이 흐름 | ||
| # 1. word[0]과 같은 칸에서만 시작 | ||
| # 2. stack에 탐색 항목(False)과 복구 항목(True)을 같이 넣음 | ||
| # 3. 탐색 항목: 마지막 글자면 True, 아니면 '*'로 표시 -> 복구 항목 push -> 다음 글자와 같은 이웃 push | ||
| # 이미 지나온 칸은 '*'라서 글자 비교에서 걸러짐 (path 집합 필요 없음) | ||
| # 4. 복구 항목: 이웃보다 먼저 넣어서 그 칸에서 나아가는 길을 다 본 뒤에 pop됨 -> 원래 글자로 되돌림 | ||
| # 5. while이 끝나면 board는 원래대로 돌아와 있으니 다음 시작점으로, 다 실패하면 False | ||
| # Time: O(m * n * 3^L), Space: O(L) - 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((False, i, j, 0)) # (복구 항목인지, x, y, word_idx) | ||
| while stack: | ||
| is_restore, x, y, word_idx = stack.pop() | ||
| if is_restore: # 이 칸으로부터 연결되는 길은 다 탐색완료하였으므로 원래 글자로 | ||
| board[x][y] = word[word_idx] | ||
| continue | ||
| if word_idx == len(word) - 1: | ||
| return True | ||
| board[x][y] = '*' | ||
| stack.append((True, x, y, word_idx)) # 이웃보다 먼저 넣어야 제일 나중에 나옴 | ||
| for k in range(4): | ||
| nx, ny = x + dxs[k], y + dys[k] | ||
| if in_range(nx, ny) and board[nx][ny] == word[word_idx + 1]: | ||
| stack.append((False, nx, ny, word_idx + 1)) | ||
| return False | ||
|
|
||
|
|
||
| #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 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 float('inf')로 했습니다만 10**10 으로 초기화한 부분이 인상적이네요.
찾아보니 모든 가능한 동전 개수 보다 항상 큰 가장 작은 대체값으로 amount + 1로 초기화를 해도 좋을 거 같습니다.
덕분에 학습되었습니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
저는 오히려 float('inf')가 더 명시적인 것 같네요. 10**10은 매번 직접 입력하기도 번거롭고, 혹시 문제 조건에서 제한 범위에 들어가면 틀릴 수도 있어서 inf로 두는 게 더 안전할 것 같네요.
amount + 1로 초기화하는 방법은 저도 배워갑니다:) 리뷰 감사합니다