-
-
Notifications
You must be signed in to change notification settings - Fork 362
[Chanz] WEEK 04 Solutions #2753
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
Changes from 7 commits
76b95a9
1403468
d532ed4
06931e4
8709455
b4381e3
0ad1fc7
ed663a6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| class Solution: | ||
| def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: | ||
|
|
||
| result = [] | ||
| combination = [] | ||
| def find_target(start, combination, target): | ||
|
|
||
| if target == 0 : # 조합 생성 완료. | ||
| result.append(combination.copy()) # pop 때문에 복사해서 append해야 함. | ||
| return | ||
|
|
||
| elif target < 0 or start >= len(candidates): | ||
| return | ||
|
|
||
| combination.append(candidates[start]) | ||
| find_target(start, combination, target-candidates[start]) # 현재 원소를 더 뽑는 경우 | ||
| combination.pop() # 현재 원소는 다시 조합에서 제거 후, 다음 원소를 뽑음 | ||
| find_target(start+1, combination, target) # 다음 원소를 뽑는 경우 | ||
|
|
||
| find_target(0, combination, target) | ||
|
|
||
| return result |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
풀이 1:
|
| 복잡도 | |
|---|---|
| Time | O(log n) |
| Space | O(1) |
피드백: 중단 조건이 left < right 이고, 매 반복마다 중간값과 오른쪽 끝 값을 비교해 범위를 절반으로 축소합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 2: Solution.maxDepth — Time: O(n) / Space: O(h)
| 복잡도 | |
|---|---|
| Time | O(n) |
| Space | O(h) |
피드백: 재귀적인 DFS로 각 노드를 한 번씩 방문하고 스택 프레임으로 깊이를 추적합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 3: Solution.mergeTwoLists — Time: O(n + m) / Space: O(1)
| 복잡도 | |
|---|---|
| Time | O(n + m) |
| Space | O(1) |
피드백: 비교를 통해 노드를 재배치하여 더미 노드를 가운데에 두고 연결 리스트를 확장합니다.
개선 제안: 현재 구현이 적절해 보입니다.
풀이 4: Solution.exist — Time: O(4^(L) * NM) / Space: O(L)
| 복잡도 | |
|---|---|
| Time | O(4^(L) * NM) |
| Space | O(L) |
피드백: 각 좌표에서 DFS를 진행하고 방문 처리를 위해 문자를 임시로 바꿔 재귀적으로 탐색합니다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class Solution: | ||
| def findMin(self, nums: List[int]) -> int: | ||
|
|
||
| left = 0 | ||
| right = len(nums) - 1 | ||
|
|
||
| while left < right: | ||
| mid = (left + right) // 2 | ||
|
|
||
| if nums[right] < nums[mid]: # right 와 mid 사이에 최소 값이 존재 | ||
|
Comment on lines
+7
to
+10
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. 탐색 중간에 정답으로 판별이 가능한 경우가 있는데 최적화 시도해보셔도 좋을 거 같습니다
Contributor
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. 정렬 된 경우인 경우 바로 반환하도록 했습니다. Leetcode에서는 기존 코드도 0ms라서.. 직접 성능 비교는 어렵군요..! 의도하신 바가 이게 맞을지 궁금하긴 합니다..ㅎㅎ |
||
| left = mid + 1 | ||
| else: | ||
| right = mid | ||
|
|
||
| return nums[left] | ||
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # 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 | ||
|
|
||
| class Solution: | ||
| def maxDepth(self, root: Optional[TreeNode]) -> int: | ||
|
|
||
| max_depth = 0 | ||
| def dfs(cur_node, cur_depth): | ||
| nonlocal max_depth | ||
| if cur_node == None: | ||
| return | ||
| cur_depth += 1 | ||
| max_depth = max(max_depth, cur_depth) | ||
|
|
||
| dfs(cur_node.left, cur_depth) | ||
| dfs(cur_node.right, cur_depth) | ||
| return | ||
|
|
||
| dfs(root, 0) | ||
| return max_depth | ||
|
Comment on lines
+9
to
+24
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. 개인적으로 외부 변수 max_depth, nonlocal 때문에 그런지 코드 따라가기가 약간 어려웠던거 같습니다. dfs 함수의 리턴 값을 활용하시면 가독성을 많이 올리실 수 있을 거 같습니다. |
||
|
|
||
|
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. 확실히 이 문제에서는 BFS보다는 DFS가 더 좋은 풀이 같네요! |
||
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # 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]: | ||
|
|
||
| if not list1: | ||
| return list2 | ||
| if not list2: | ||
| return list1 | ||
|
|
||
| cursor = ListNode() | ||
| result = cursor | ||
| cursor.next = list1 | ||
|
|
||
| while cursor.next: | ||
| while list2 and list2.val <= cursor.next.val: | ||
| temp_1 = cursor.next | ||
| temp_2 = list2.next | ||
|
|
||
| cursor.next = list2 | ||
| list2.next = temp_1 | ||
| list2 = temp_2 | ||
|
|
||
| cursor = cursor.next | ||
|
|
||
| if list2: | ||
| cursor.next = list2 | ||
|
Comment on lines
+18
to
+30
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. cursor에 어떤 값이 담기고 list2와 어떻게 비교되어서 동작하는건지 따라가기가 조금 어려운 거 같습니다. 스왑 로직도 있고 해서 그런 거 같은데 조금 더 단순하게 풀어보셔도 좋을 거 같습니다.
Contributor
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. 맞습니다. 저도 구현하면서 스왑하고 이런게 헷갈리더라고요. |
||
|
|
||
| return result.next | ||
|
|
||
|
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. 저는 재귀로 풀었는데, 이렇게도 풀 수 있겠네요! |
||
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 반복을 통해 각 비트를 확인하고 카운트를 증가시킵니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| class Solution: | ||
| def hammingWeight(self, n: int) -> int: | ||
|
|
||
| # 공간복잡도 : 변수 2개 및 상수만 사용하므로, O(1) | ||
| # 시간복잡도 : bit counting한 이후에 n을 1/2하므로 O(logn) | ||
| bit_count = 0 | ||
| while n > 0: | ||
| if n % 2 == 1: | ||
| bit_count += 1 | ||
| n //= 2 | ||
|
|
||
| return bit_count | ||
|
|
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 공백 제거와 소문자화 후 양방향 탐색으로 팔린드롬 여부를 판단합니다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| class Solution: | ||
| def isPalindrome(self, s: str) -> bool: | ||
|
|
||
| # 공간 복잡도 : 문자열의 길이만큼만 공간을 사용합니다. 따라서 O(n) | ||
| # 시간 복잡도 : 문자열의 길이 만큼 순회를 1번 하고, 이후에 한번 더 순회를 하나 길이의 1/2 까지만 순회를 합니다. O(n) | ||
| alpha_num_str = "" | ||
| for ch in s: | ||
| if ch.isalnum(): | ||
| alpha_num_str += ch.lower() | ||
|
|
||
| end_idx = len(alpha_num_str) - 1 | ||
| for idx, ch in enumerate(alpha_num_str): | ||
| if idx >= end_idx: | ||
| return True | ||
| if ch != alpha_num_str[end_idx]: | ||
| return False | ||
| end_idx -= 1 | ||
| return True | ||
|
|
|
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. 🏷️ 알고리즘 패턴 분석
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| class Solution: | ||
| def exist(self, board: List[List[str]], word: str) -> bool: | ||
|
|
||
| def dfs(current, word_idx): | ||
| x, y = current | ||
|
|
||
| if word_idx == len(word): | ||
| return True | ||
|
|
||
| if x < 0 or x >= len(board) or y < 0 or y >= len(board[0]): | ||
| return False | ||
|
|
||
| if board[x][y] != word[word_idx] : | ||
| return False | ||
|
|
||
| tmp = board[x][y] | ||
| board[x][y] = '#' | ||
|
|
||
| found = (dfs((x-1, y), word_idx+1) or | ||
| dfs((x+1, y), word_idx+1) or | ||
| dfs((x, y-1), word_idx+1) or | ||
| dfs((x, y+1), word_idx+1)) | ||
|
|
||
| board[x][y] = tmp | ||
|
|
||
| return found | ||
|
Comment on lines
+4
to
+26
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. 요거 돌려보면 runtime이 50% 정도 나오는데 최적화 시도해보셔도 좋을 거 같습니다. 불필요한 탐색을 안하도록 해보시면 될 거 같아요. |
||
|
|
||
| for x, rows in enumerate(board): | ||
| for y, cell in enumerate(rows): | ||
| if dfs((x, y), 0) == True : | ||
| return True | ||
| return False | ||
|
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. 이 문제를 DFS로 풀 수 있다는 것은 전혀 생각하지 못했네요...! 감사합니다! |
||
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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 백트래킹으로 중복 조합을 제거하지 않고 각 후보를 계속 사용 가능하도록 시작 인덱스를 유지합니다. 종료 조건과 가지치기가 있어도 최악의 경우 지수 시간 복잡도에 근접합니다.
개선 제안: 현재 구현이 적절해 보입니다.