-
-
Notifications
You must be signed in to change notification settings - Fork 363
[Zero-1016] WEEK 03 Solutions #2708
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
base: main
Are you sure you want to change the base?
Changes from all commits
5c31066
64e0213
31eec44
66960cd
faa8fb0
a642d65
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,88 @@ | ||
| /** | ||
| * Combination Sum1 (같은 숫자 재사용 가능) — 비효율 버전 | ||
| * | ||
| * 표기: | ||
| * n = candidates 길이 | ||
| * T = target | ||
| * M = candidates 중 최솟값 | ||
| * D = T / M (재귀 트리의 최대 깊이) | ||
| * 시간 복잡도: O(nᴰ × D) | ||
| * - start 인덱스가 없어 매번 0부터 탐색 → [2,2,3], [2,3,2], [3,2,2] 같은 | ||
| * 순열을 전부 방문 (조합 하나당 최대 D! 개) | ||
| * - 정답 발견 시 경로 복사 O(D), 후처리(sort + join + Set) 비용은 탐색량에 묻힘 | ||
| * | ||
| * 공간 복잡도: O(D! × 정답 개수 × D) | ||
| * - 중복 조합이 제거 전까지 combinations에 전부 쌓임 → OOM 위험 | ||
| * - 재귀 스택: O(D) | ||
| */ | ||
| function combinationSum1(candidates: number[], target: number): number[][] { | ||
| const combinations: number[][] = []; | ||
|
|
||
| const backtrack = (currentPath: number[], currentSum: number) => { | ||
| const pathCopy = [...currentPath]; | ||
| const remainingTarget = target - currentSum; | ||
|
|
||
| if (remainingTarget === 0) { | ||
| combinations.push(pathCopy); | ||
| } | ||
|
|
||
| for (let i = 0; i < candidates.length; i++) { | ||
| const candidate = candidates[i]; | ||
|
|
||
| if (remainingTarget - candidate >= 0) { | ||
| pathCopy.push(candidate); | ||
| backtrack(pathCopy, currentSum + candidate); | ||
| pathCopy.pop(); | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| backtrack([], 0); | ||
|
|
||
| // 중복 조합 제거 후 반환 | ||
| return [...new Set(combinations.map((path) => path.sort().join(",")))].map( | ||
| (str) => str.split(",").map(Number), | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Combination Sum2 (같은 숫자 재사용 가능) — 최적화 버전 | ||
| * | ||
| * 표기: | ||
| * n = candidates 길이 | ||
| * T = target | ||
| * M = candidates 중 최솟값 | ||
| * D = T / M (재귀 트리의 최대 깊이) | ||
| * | ||
| * 시간 복잡도: O(nᴰ × D) | ||
| * - Big-O 상한은 1번과 같지만 실제 탐색량은 훨씬 작음: | ||
| * 1) start 인덱스 → 순열 중복 탐색 원천 차단 (조합당 정확히 1회 방문) | ||
| * 2) 정렬 + break → 무효한 가지를 통째로 절단 | ||
| * - 정렬 비용 O(n log n)은 지수 항에 묻힘 | ||
| * | ||
| * 공간 복잡도: O(D + 정답 개수 × D) | ||
| * - 재귀 스택 + 공유 path: O(D) | ||
| * - 출력 배열: 정답 개수 × 평균 길이 (출력 자체라 최소 비용) | ||
| */ | ||
| function combinationSum2(candidates: number[], target: number): number[][] { | ||
| const combinations: number[][] = []; | ||
| candidates.sort((a, b) => a - b); | ||
|
|
||
| const backtrack = (start: number, path: number[], remaining: number) => { | ||
| if (remaining === 0) { | ||
| combinations.push([...path]); | ||
| return; | ||
| } | ||
|
|
||
| for (let i = start; i < candidates.length; i++) { | ||
| if (candidates[i] > remaining) break; | ||
|
|
||
| path.push(candidates[i]); | ||
| backtrack(i, path, remaining - candidates[i]); | ||
| path.pop(); | ||
| } | ||
| }; | ||
|
|
||
| backtrack(0, [], target); | ||
| return combinations; | ||
| } |
|
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 @@ | ||
| /** | ||
| * 시간 복잡도 O(n) | ||
| * 공간 복잡도 O(1) | ||
| */ | ||
| function numDecodings(s: string): number { | ||
| const n = s.length; | ||
| if (n === 0 || s[0] === "0") return 0; | ||
|
|
||
| // prev2 = dp[i-2], prev1 = dp[i-1] | ||
| let prev2 = 1; // dp[0] | ||
| let prev1 = 1; // dp[1] (s[0]이 '0'이 아님을 위에서 보장) | ||
|
|
||
| for (let i = 2; i <= n; i++) { | ||
| let cur = 0; | ||
| const one = s[i - 1]; // 마지막 한 자리 | ||
| const two = Number(s.slice(i - 2, i)); // 마지막 두 자리 | ||
|
|
||
| if (one !== "0") cur += prev1; // 한 자리로 끊기 | ||
| if (two >= 10 && two <= 26) cur += prev2; // 두 자리로 끊기 | ||
|
|
||
| prev2 = prev1; | ||
| prev1 = cur; | ||
| } | ||
| return prev1; | ||
| } |
|
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,17 @@ | ||
| /** | ||
| * 시간 복잡도 O(n) | ||
| * 공간 복잡도 O(1) | ||
| */ | ||
| function maxSubArray(nums: number[]): number { | ||
| let currentSum = 0; | ||
| let maxSum = -Infinity; | ||
|
|
||
| for (let i = 0; i < nums.length; i++) { | ||
| let n = nums[i]; | ||
|
|
||
| currentSum = Math.max(currentSum + n, n); | ||
| maxSum = Math.max(maxSum, currentSum); | ||
| } | ||
|
|
||
| return maxSum; | ||
| } |
|
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 @@ | ||
| /** | ||
| * 시간 복잡도 O(N) | ||
| * 공간 복잡도 O(N) | ||
| */ | ||
| function hammingWeight1(n: number): number { | ||
| const bitNumber = n.toString(2); | ||
| return bitNumber.split("").filter((char) => char === "1").length; | ||
| } | ||
|
|
||
| /** | ||
| * 시간 복잡도 O(N) | ||
| * 공간 복잡도 O(1) | ||
| */ | ||
| function hammingWeight2(n: number): number { | ||
|
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. 비트연산자로 하는 풀이 배워갑니다! |
||
| let count = 0; | ||
| while (n > 0) { | ||
| count += n & 1; // 마지막 비트가 1인지 확인 | ||
| n = n >>> 1; // 우측으로 1비트 시프트 (부호 없는 우측 시프트) | ||
| } | ||
| 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,34 @@ | ||
| /** | ||
| * 시간 복잡도 O(N) | ||
| * 공간 복잡도 O(1) | ||
| */ | ||
| const isNotAlphanumeric = /[^a-zA-Z0-9]/; | ||
|
|
||
| function isPalindrome(s: string): boolean { | ||
| let leftCursor = 0; | ||
| let rightCursor = s.length - 1; | ||
|
|
||
| while (leftCursor < rightCursor) { | ||
| const currentLeftAlpha = s[leftCursor]; | ||
| const currentRightAlpha = s[rightCursor]; | ||
|
|
||
| if (isNotAlphanumeric.test(currentLeftAlpha)) { | ||
| leftCursor++; | ||
| continue; | ||
| } | ||
|
|
||
| if (isNotAlphanumeric.test(currentRightAlpha)) { | ||
| rightCursor--; | ||
| continue; | ||
| } | ||
|
|
||
| if (currentLeftAlpha.toLowerCase() === currentRightAlpha.toLowerCase()) { | ||
| leftCursor++; | ||
| rightCursor--; | ||
| } 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.
🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
풀이 1:
combinationSum1— Time: O(2^n) / Space: O(D)피드백: 중복 순열 탐색으로 인해 불필요한 탐색이 많아 지수적 시간 복잡도가 증가합니다.
개선 제안: 고려해볼 만한 대안: start 인덱스를 도입해 중복 순열을 제거하고, 후보를 정렬한 뒤 가지치기를 적용하면 시간 복잡도를 크게 줄일 수 있습니다.
풀이 2:
combinationSum2— Time: ❌ O(nᴰ × D) → O(2^n) / Space: ❌ O(D + 정답 개수 × D) → O(D)피드백: 정렬과 시작 인덱스 도입으로 중복 탐색을 막고, 남는 값을 빠르게 단절하는 가지치기 방식이 효과적입니다.
개선 제안: 현재 구현이 적절해 보입니다.