Skip to content

Commit 6783b72

Browse files
committed
add combination sum solution
1 parent 95ce67e commit 6783b72

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.List;
2+
import java.util.ArrayList;
3+
/**
4+
์ค‘๋ณต ๋˜์ง€ ์•Š์€ ์š”์†Œ๋“ค์ด ๋“ค์–ด์žˆ๋Š” candidates ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง€๊ณ  target ๊ฐ’์ด ์ฃผ์–ด์ง„๋‹ค.
5+
ํ•ฉ์ด target๊ณผ ๊ฐ™์€ ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์กฐํ•ฉ์„ ๋ชจ๋‘ ๋ฐ˜ํ™˜ํ•˜์‹œ์˜ค.
6+
*/
7+
class Solution {
8+
9+
List<List<Integer>> answer = new ArrayList<>();
10+
11+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
12+
combination(0, candidates, target, 0, new ArrayList<>());
13+
return answer;
14+
}
15+
16+
// ์‹œ๊ฐ„๋ณต์žก๋„ O(2^target)
17+
public void combination(int idx, int[] candidates, int target, int currentSum, List<Integer> comb) {
18+
// ๋ˆ„์  ํ•ฉ์ด ๋„˜์œผ๋ฉด
19+
if (currentSum > target) {
20+
return;
21+
}
22+
23+
// ๋ˆ„์  ํ•ฉ์ด ํƒ€๊ฒŸ ๊ฐ’๊ณผ ๊ฐ™์œผ๋ฉด
24+
if (currentSum == target) {
25+
answer.add(new ArrayList<>(comb));
26+
return;
27+
}
28+
29+
for (int i = idx; i < candidates.length; i++) {
30+
comb.add(candidates[i]);
31+
combination(i, candidates, target, currentSum + candidates[i], comb);
32+
comb.remove(comb.size() - 1);
33+
}
34+
}
35+
}
36+

0 commit comments

Comments
ย (0)