Skip to content

Commit f3f75a1

Browse files
committed
combination sum solution
1 parent c826585 commit f3f75a1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

โ€Žcombination-sum/Yn3-3xh.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
[๋ฌธ์ œํ’€์ด]
3+
- target ์ˆซ์ž๋ฅผ ์ฃผ์–ด์ง„ ๋ฐฐ์—ด๋กœ ๋‚˜๋ˆ ๋ณด๋ฉด์„œ 0์ด ๋˜๋Š” ๊ฒƒ๋“ค์„ ๊ณ ๋ฅด๋ฉด ๋˜์ง€ ์•Š์„๊นŒ?
4+
- dfs๋กœ ํ’€์–ด๋ณด์ž.
5+
time: O(2^N), space: O(N);
6+
7+
[ํšŒ๊ณ ]
8+
!!! dfs์—์„œ ๊ธฐ์กด ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ดํ›„์— ๋ณ€๊ฒฝ๋  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์ƒˆ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•ด์„œ ๋„ฃ์–ด์ค˜์•ผ ํ•œ๋‹ค. !!!
9+
10+
DP๋กœ๋„ ํ’€์–ด๋ณด๋ ค๊ณ  ํ–ˆ์ง€๋งŒ, ์†”๋ฃจ์…˜์„ ๋ด๋„ ๋‚ด๊ฐ€ ํ’€ ์ˆ˜ ์—†์„ ๊ฒƒ ๊ฐ™์•˜๋‹ค..
11+
*/
12+
class Solution {
13+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
14+
List<List<Integer>> results = new ArrayList<>();
15+
dfs(candidates, target, 0, results, new ArrayList<>(), 0);
16+
return results;
17+
}
18+
19+
private void dfs(int[] candidates, int target, int index, List<List<Integer>> results, List<Integer> result, int sum) {
20+
if (sum == target) {
21+
results.add(new ArrayList<>(result));
22+
return;
23+
}
24+
25+
if (sum > target || index >= candidates.length) {
26+
return;
27+
}
28+
29+
int num = candidates[index];
30+
result.add(num);
31+
dfs(candidates, target, index, results, result, sum + num);
32+
33+
result.remove(result.size() - 1);
34+
dfs(candidates, target, index + 1, results, result, sum);
35+
}
36+
}
37+

0 commit comments

Comments
ย (0)