Skip to content
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

[moonhyeok] Week3 #801

Merged
merged 5 commits into from
Dec 28, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions combination-sum/mike2ox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* source: https://leetcode.com/problems/combination-sum/
* 풀이방법: 재귀를 이용하여 모든 조합을 탐색
*
* 시간복잡도: O(n^m) (n: candidates의 길이, m: target을 만들기 위한 최대 반복 횟수)
* 공간복잡도: O(n^m) (n: candidates의 길이, m: target을 만들기 위한 최대 반복 횟수)
*
* Note
* - 당장에 구현하려다보니 재귀를 이용한 방법으로 구현. => 추후 리팩토링 필요
*/
function combinationSum(candidates: number[], target: number): number[][] {
if (target === 0) return [[]];
if (target < 0) return [];

const result: number[][] = [];

for (let i = 0; i < candidates.length; i++) {
const num = candidates[i];
const subCombos = combinationSum(candidates.slice(i), target - num);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드가 가독성이 좋아서 읽기 편했어요! 감사합니다 :)

큰 차이는 없을 것 같지만 slice를 사용하면 배열 복사가 매번 발생하게 되어서 현재 idx를 파라미터로 넘기는 방법을 사용해도 괜찮을거 같아요!
로직 자체는 slice를 사용하는 것과 동일하게 현재 인덱스부터 끝까지 탐색한다는 면에서 같은 동작을 합니다.

function combinationSumHelper(candidates: number[], target: number, startIndex: number): number[][] {
  if (target === 0) return [[]];
  if (target < 0) return [];

  const result: number[][] = [];

  for (let i = startIndex; i < candidates.length; i++) {
    const num = candidates[i];
    const subCombos = combinationSumHelper(candidates, target - num, i); 
    // i를 넘기면, 중복 사용 가능하고 i 이전 것은 다시 보지 않음

    for (const combo of subCombos) {
      result.push([num, ...combo]);
    }
  }

  return result;
}

function combinationSum(candidates: number[], target: number): number[][] {
  return combinationSumHelper(candidates, target, 0);
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제에서 제공하는 입력 형식 그대로 하려다보니 저렇게 되었는데 올려주신 방법이 훨씬 효율적이네요!
감사합니다 :)


for (const combo of subCombos) {
result.push([num, ...combo]);
}
}

return result;
}
Loading