-
-
Notifications
You must be signed in to change notification settings - Fork 362
[freemjstudio] WEEK 03 Solutions #2734
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
|
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. 생각도 안 하고 바로 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. 오 dp 로도 풀수있군용.. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| class Solution: | ||
| def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: | ||
| answer = [] | ||
|
|
||
| def backtracking(start_idx, total, path): | ||
| if target == total: | ||
| answer.append(path[:]) # 새로운 리스트 객체를 만들어서 저장함. | ||
| # 리스트가 mutable 객체이므로 path[:] 로 복사하지 않으면 path 가 바뀔 때 answer 안의 값도 바뀌게 된다. | ||
| return | ||
|
|
||
| if target < total: | ||
| return | ||
|
|
||
| for idx in range(start_idx, len(candidates)): | ||
| new_node = candidates[idx] # 동일한 숫자 재사용 가능함. start_idx 도 포함한다. | ||
| path.append(new_node) | ||
|
|
||
| backtracking(idx, total + new_node, path) | ||
| # 선택 취소 | ||
| path.pop() | ||
|
|
||
| backtracking(0, 0, []) | ||
| return answer |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 연속된 두 자리 해석 여부를 체크하고, 한 자리 해석 가능 여부에 따라 dp 값을 누적한다. 개선 제안: 초기 입력 문자열의 길이가 0인 경우를 안전하게 처리하도록 보강하면 안정성이 올라간다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| class Solution: | ||
| def numDecodings(self, s: str) -> int: | ||
| # invalid case | ||
| if s[0] == "0": | ||
| return 0 | ||
|
|
||
| dp = [0] * (len(s)+1) # 앞에서부터 i개 문자를 해석하는 방법 | ||
|
|
||
| dp[0] = 1 | ||
| dp[1] = 1 | ||
| for i in range(2, len(s)+1): | ||
| one_digit = s[i-1] | ||
| two_digits = int(s[i-2]) * 10 + int(s[i-1]) | ||
| if one_digit != '0': # 현재 숫자를 한자리로 해석하는 경우. (0 은 매칭되는 알파벳이 없으므로 제외) | ||
| dp[i] += dp[i-1] | ||
|
|
||
| if 10 <= two_digits <= 26: # 현재 숫자를 바로 앞자리 숫자와 묶어서 두자리로 해석하는 경우 | ||
| dp[i] += dp[i-2] | ||
|
|
||
| return dp[len(s)] |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 현재 구현은 각 i에 대해 dp[i]를 갱신하고 최댓값을 필요시마다 반환한다. 개선 제안: 최적화하려면 extra dp 배열 없이 누적 변수 두 개로 구현 가능하다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| class Solution: | ||
| def maxSubArray(self, nums: List[int]) -> int: | ||
| n = len(nums) | ||
| if n == 1: | ||
| return nums[0] | ||
|
|
||
| dp = [0] * n | ||
| dp[0] = nums[0] | ||
| # dp[i] = i에서 끝나는 부분 배열의 최대 합 | ||
|
|
||
| for i in range(1, n): | ||
| dp[i] = max(nums[i], dp[i-1] + nums[i]) | ||
|
|
||
| return max(dp) |
|
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. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 첫 번째 구현은 파이썬 내장 함수로 간단하고 두 번째는 비트 연산으로도 가능하다. 개선 제안: 비트 카운트 최적화를 위해 Brian Kernighan의 알고리즘을 사용할 수 있다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| class Solution: | ||
| def hammingWeight(self, n: int) -> int: | ||
| binary = bin(n) | ||
| return binary.count("1") | ||
|
Comment on lines
+2
to
+4
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. Hamming Weight이 뭘까하고 찾아봤는데, 상황에 딱 맞는 네이밍이네요. |
||
|
|
||
| # bin() 을 못쓰는 경우의 풀이 | ||
| class Solution: | ||
| def hammingWeight(self, n: int) -> int: | ||
| count = 0 | ||
|
|
||
| while n > 0: | ||
| count += n % 2 | ||
| 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,21 @@ | ||
| class Solution: | ||
| def isPalindrome(self, s: str) -> bool: | ||
| characters = "abcdefghijklmnopqrstuvwxyz0123456789" | ||
| s = s.lower() | ||
|
|
||
| filtered = "" | ||
| for ch in s: | ||
| if ch in characters: | ||
|
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. 문제 조건에서 s가 ascii로 제한되어 있으니 isalnum()을 쓰는 것도 괜찮을 것 같아 보이네요!
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. 오 그런 함수가 있군요 감사합니다!! |
||
| filtered += ch | ||
|
|
||
| n = len(filtered) | ||
| left = 0 | ||
| right = n-1 | ||
| while left <= n//2 and right >= n//2: | ||
| if filtered[left] == filtered[right]: | ||
| left += 1 | ||
| right -= 1 | ||
| else: | ||
| return False | ||
|
|
||
| return True | ||
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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 중복 조합 탐색을 막기 위해 start_idx를 유지하고, 같은 원소를 재사용 가능하게 하여 모든 조합을 생성한다.
개선 제안: 현재 구현이 적절해 보입니다.