Skip to content

Commit b433c11

Browse files
committed
combination sum solution
1 parent 6803e12 commit b433c11

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

โ€Žcombination-sum/smosco.jsโ€Ž

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Combination Sum
3+
*
4+
* ํ•ต์‹ฌ ์•„์ด๋””์–ด:
5+
* - DFS + ๋ฐฑํŠธ๋ž˜ํ‚น์œผ๋กœ ๋ชจ๋“  ์กฐํ•ฉ ํƒ์ƒ‰
6+
* - ๊ฐ™์€ ์ˆซ์ž๋ฅผ ์—ฌ๋Ÿฌ ๋ฒˆ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
7+
* - start ์ธ๋ฑ์Šค๋กœ ์ค‘๋ณต ์กฐํ•ฉ ๋ฐฉ์ง€ ([2,3]๊ณผ [3,2] ๊ฐ™์€ ๊ฒƒ)
8+
*
9+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(N^(T/M)) - N: ํ›„๋ณด ๊ฐœ์ˆ˜, T: ํƒ€๊ฒŸ, M: ์ตœ์†Œ๊ฐ’
10+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(T/M) - ์žฌ๊ท€ ๊นŠ์ด
11+
*/
12+
13+
const combinationSum = (candidates, target) => {
14+
const result = [];
15+
16+
const dfs = (remain, start, path) => {
17+
// Base case: ํƒ€๊ฒŸ ๋‹ฌ์„ฑ
18+
if (remain === 0) {
19+
result.push([...path]); // ํ˜„์žฌ ๊ฒฝ๋กœ ์ €์žฅ
20+
return;
21+
}
22+
23+
// Base case: ํƒ€๊ฒŸ ์ดˆ๊ณผ (pruning)
24+
if (remain < 0) return;
25+
26+
// ๋ชจ๋“  ํ›„๋ณด ํƒ์ƒ‰
27+
for (let i = start; i < candidates.length; i++) {
28+
// ๊ฐ€์ง€์น˜๊ธฐ: ๋‚จ์€ ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ์Šคํ‚ต
29+
if (candidates[i] > remain) continue;
30+
31+
// ์„ ํƒ
32+
path.push(candidates[i]);
33+
34+
// ํƒ์ƒ‰ (i๋ถ€ํ„ฐ ์‹œ์ž‘ - ๊ฐ™์€ ์ˆซ์ž ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅ)
35+
dfs(remain - candidates[i], i, path);
36+
37+
// ๋˜๋Œ๋ฆฌ๊ธฐ (๋ฐฑํŠธ๋ž˜ํ‚น)
38+
path.pop();
39+
}
40+
};
41+
42+
dfs(target, 0, []);
43+
return result;
44+
};

0 commit comments

Comments
ย (0)