Skip to content

Commit

Permalink
add solution : 39. Combination Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
mmyeon committed Dec 26, 2024
1 parent b2282f5 commit 130e582
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions combination-sum/mmyeon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
* - ์ค‘๋ณต ํฌํ•จํ•˜์—ฌ ๋ชจ๋“  ์กฐํ•ฉ ๊ตฌํ•ด์•ผ ํ•˜๋‹ˆ๊นŒ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ํ’€๊ธฐ
* - ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ํƒ์ƒ‰ํ•ด์•ผํ•˜๋Š” ํƒ€๊ฒŸ ์ค„์—ฌ๊ฐ€๋ฉด์„œ ์กฐํ•ฉ ๋งŒ๋“ค๊ธฐ
* - ๋™์ผ ์กฐํ•ฉ์ถ”๊ฐ€๋˜์ง€ ์•Š๋„๋ก, startIndex ์ถ”๊ฐ€ํ•˜์—ฌ ๋‹ค์Œ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์ˆœํšŒํ•˜๋„๋ก ์ œํ•œ
*
*
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n^target)
* - candidates ๋ฐฐ์—ด ๊ธธ์ด n๋งŒํผ ์žฌ๊ท€๊ฐ€ ํ˜ธ์ถœ๋˜๊ณ , ๊ฐ ํ˜ธ์ถœ์€ target ๊ธธ์ด ๋งŒํผ ์ค‘์ฒฉ๋˜๋‹ˆ๊นŒ O(n^target)
*
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(target)
* - ์ตœ์•…์˜ ๊ฒฝ์šฐ target๋งŒํผ ์žฌ๊ท€ ํ˜ธ์ถœ๋˜๋‹ˆ๊นŒ O(target)
*
*/

function combinationSum(candidates: number[], target: number): number[][] {
const result: number[][] = [];

const dfs = (target: number, combination: number[], startIndex: number) => {
if (target === 0) {
result.push([...combination]);
return;
}

if (target < 0) return;

for (let i = startIndex; i < candidates.length; i++) {
combination.push(candidates[i]);
dfs(target - candidates[i], combination, i);
combination.pop();
}
};

dfs(target, [], 0);

return result;
}

0 comments on commit 130e582

Please sign in to comment.