-
-
Notifications
You must be signed in to change notification settings - Fork 363
[parkhojeong] WEEK 03 Solutions #2727
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 all commits
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,29 @@ | ||
| from typing import List | ||
|
|
||
| class Solution: | ||
| def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: | ||
| candidates = [x for x in sorted(candidates) if x <= target] | ||
| res = self.dfs(candidates, target, [], 0) | ||
|
|
||
| return res | ||
|
|
||
| def dfs( | ||
| self, candidates: List[int], target: int, | ||
| visited: List[int], prev_sum: int | ||
| ) -> List[List[int]]: | ||
| if prev_sum == target: | ||
| return [visited] | ||
|
|
||
| arr = [] | ||
| for i in range(len(candidates)): | ||
| if prev_sum + candidates[i] > target: | ||
| continue | ||
|
|
||
| res = self.dfs( | ||
| candidates[i:], target, | ||
| visited + [candidates[i]], prev_sum + candidates[i] | ||
| ) | ||
| for item in res: | ||
| arr.append(item) | ||
|
|
||
| return arr |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 0 처리와 구간 분할 로직이 꼼꼼하지만, 동적계획법으로 한 번에 해결하는 방법이 더 명확하고 안전하다. 개선 제안: 현재 구현 대신 DP 1차원 배열로 피연산자별 경우의 수를 누적하는 방식으로 구현을 정리하는 것을 고려해볼 만합니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| class Solution: | ||
| def numDecodings(self, s: str) -> int: | ||
| if s[0] == "0": | ||
| return 0 | ||
|
|
||
| for i in range(1, len(s)): | ||
| if s[i] == "0": | ||
| if s[i - 1] == "0": | ||
| return 0 | ||
| if s[i - 1] >= "3": | ||
| return 0 | ||
|
|
||
| splited_arr = [] | ||
|
|
||
| i = len(s) - 1 | ||
| j = len(s) | ||
| while i > 0: | ||
| if s[i - 1] + s[i] >= "27": | ||
| splited_arr.append(s[i:j]) | ||
| i -= 1 | ||
| j = i + 1 | ||
| elif s[i] == "0": | ||
| splited_arr.append(s[i + 1:j]) | ||
| i -= 2 | ||
|
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. 0이 들어가는 경우를 먼저 나누고 문자열을 구간별로 분리해서 경우의 수를 계산하신 흐름을 잘 봤습니다! 제가 생각한 DP 방식과 달라서 이런 식으로도 풀 수 있다는 걸 배웠어요!
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. 조건 중에 0이 중요한 부분이더라구요. 0을 기준으로 입력 값을 쪼개준 뒤, 각 경우의 수를 구해 곱해주도록 해보았습니다 :) |
||
| j = i + 1 | ||
| else: | ||
| i -= 1 | ||
|
|
||
| splited_arr.append(s[:j]) | ||
|
|
||
| result = 1 | ||
| for s in splited_arr: | ||
| result *= self.count_num(s) | ||
|
|
||
| return result | ||
|
|
||
| def count_num(self, s: str) -> int: | ||
| if len(s) <= 1: | ||
| return 1 | ||
|
|
||
| prev2, prev1, cur = 1, 2, 2 | ||
| for i in range(2, len(s)): | ||
| cur = prev2 + prev1 | ||
| prev2, prev1 = prev1, cur | ||
|
|
||
| return cur | ||
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 처음 구현은 모든 값의 최댓값을 추적한 뒤 부분 구간을 분해하는 방식으로 시작하고, 이후 불필요한 연산이 있다. 개선 제안: 불필요한 0 제거와 복잡한 배열 재구성을 제거하고 Kadane의 간단한 형태로 재구현하는 것이 좋습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import sys | ||
| from typing import List | ||
|
|
||
| class Solution: | ||
| def maxSubArray(self, nums: List[int]) -> int: | ||
| max_val = -sys.maxsize | ||
|
|
||
| for num in nums: | ||
| max_val = max(max_val, num) | ||
|
|
||
| nums = [x for x in nums if x != 0] | ||
| if not nums: | ||
| return max_val | ||
|
|
||
| arr = [] | ||
| arr.append(nums[0]) | ||
| for i in range(1, len(nums)): | ||
| if nums[i] * nums[i - 1] > 0: | ||
| arr[-1] += nums[i] | ||
| else: | ||
| arr.append(nums[i]) | ||
|
|
||
| for num in arr: | ||
| max_val = max(max_val, num) | ||
|
|
||
| while len(arr) >= 2: | ||
| if arr[0] < 0: | ||
| arr = arr[1:] | ||
| if arr[-1] < 0: | ||
| arr = arr[:-1] | ||
|
|
||
| max_val = max(max_val, arr[0]) | ||
| if len(arr) >= 2: | ||
| arr[1] = arr[0] + arr[1] | ||
| arr = arr[1:] | ||
|
|
||
| max_val = max(max_val, arr[-1]) | ||
| if len(arr) >= 2: | ||
| arr[-2] = arr[-1] + arr[-2] | ||
| arr = arr[:-1] | ||
|
|
||
| max_val = max(max_val, arr[0]) | ||
|
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. 연속된 합에 대한 문제라 + - + - + - ... 형태로 데이터를 정리를 먼저 해봤어요. 이후 최대값을 그리디 방식으로 구하는 걸로 해결해봤습니다 :) |
||
|
|
||
| return max_val | ||
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 루프가 n 비트에 대해 실행되므로 입력 정수의 비트 길이에 비례한다. 개선 제안: n & (n-1) 기법으로 1비트를 제거하며 반복 횟수를 비트 수만큼 줄일 수 있습니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| class Solution: | ||
| def hammingWeight(self, n: int) -> int: | ||
| count = 0 | ||
|
|
||
| while n > 0: | ||
| count += n % 2 | ||
| n = n // 2 | ||
|
|
||
| return 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,8 @@ | ||
| class Solution: | ||
| def isPalindrome(self, s: str) -> bool: | ||
| normalized_str = "" | ||
| for ch in s: | ||
| if ch.isalnum(): | ||
| normalized_str += ch.lower() | ||
|
|
||
| return normalized_str == normalized_str[::-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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 정확히는 각 재귀에서 남은 후보군의 길이에 비례하여 탐색이 늘어나며 중복 제거를 위해 정렬 및 증가하는 방향으로 탐색한다.
개선 제안: 현재 구현은 불필요한 중복 분기를 줄이고, 가지치기와 메모이제이션을 도입하면 속도가 개선될 여지가 있습니다.