Skip to content

Commit 9e90dec

Browse files
committed
solve: combination sum
1 parent b47d55b commit 9e90dec

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

combination-sum/wogha95.js

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// 2차
2+
// 몫을 활용하여 시간복잡도를 줄이고자 하였으나 generateSubResult에서 추가 시간발생으로 유의미한 결과를 발견하지 못했습니다.
3+
// TC: O(C^2 * T)
4+
// SC: O(T)
5+
// C: candidates.length, T: target
6+
7+
/**
8+
* @param {number[]} candidates
9+
* @param {number} target
10+
* @return {number[][]}
11+
*/
12+
var combinationSum = function (candidates, target) {
13+
const result = [];
14+
// 'q' means 'quotient'.
15+
const qList = candidates.map((candidate) => Math.floor(target / candidate));
16+
17+
dfs([], 0);
18+
19+
return result;
20+
21+
function dfs(selectedQList, total) {
22+
if (total > target) {
23+
return;
24+
}
25+
26+
if (total === target) {
27+
result.push(generateSubResult(selectedQList));
28+
return;
29+
}
30+
31+
const currentIndex = selectedQList.length;
32+
for (let q = qList[currentIndex]; q >= 0; q--) {
33+
selectedQList.push(q);
34+
dfs(selectedQList, total + candidates[currentIndex] * q);
35+
selectedQList.pop();
36+
}
37+
}
38+
39+
function generateSubResult(selectedQList) {
40+
return selectedQList
41+
.map((q, index) => new Array(q).fill(candidates[index]))
42+
.flat();
43+
}
44+
};
45+
46+
// 1차
47+
// dfs를 활용하여 각 요소를 추가 -> 재귀 -> 제거로 순회합니다.
48+
// TC: O(C^T)
49+
// SC: O(T)
50+
// C: candidates.length, T: target
51+
52+
/**
53+
* @param {number[]} candidates
54+
* @param {number} target
55+
* @return {number[][]}
56+
*/
57+
var combinationSum = function (candidates, target) {
58+
const result = [];
59+
60+
dfs([], 0, 0);
61+
62+
return result;
63+
64+
function dfs(subResult, total, currentIndex) {
65+
if (total > target) {
66+
return;
67+
}
68+
69+
if (total === target) {
70+
result.push([...subResult]);
71+
return;
72+
}
73+
74+
if (currentIndex === candidates.length) {
75+
return;
76+
}
77+
78+
const candidate = candidates[currentIndex];
79+
subResult.push(candidate);
80+
dfs(subResult, total + candidate, currentIndex);
81+
subResult.pop();
82+
dfs(subResult, total, currentIndex + 1);
83+
}
84+
};

0 commit comments

Comments
 (0)