Skip to content

Commit 4846bd7

Browse files
committed
combination-sum
1 parent c33a6c8 commit 4846bd7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

โ€Žcombination-sum/taekwon-dev.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* ์•Œ๊ณ ๋ฆฌ์ฆ˜: ๋ฐฑํŠธ๋ž™ํ‚น
3+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n^t)
4+
* - n: candidates.lenth
5+
* - t: target / candidates์˜ ์ตœ์†Ÿ๊ฐ’
6+
* - ์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ดํ•ดํ•ด๋ณด์ž!
7+
*
8+
* - candidates: [2, 3], target: 6
9+
* - [2] -> [2, 2] -> [2, 2, 2] -> OK (์—ฌ๊ธฐ์„œ ์ƒ๊ฐํ•ด๋ณด๋ฉด, ์•„ ์žฌ๊ท€๋ฅผ ์ตœ๋Œ€ 6/2 ๋งŒํผ ํƒ€๊ณ  ๋“ค์–ด๊ฐ€๊ฒ ๊ตฐ?)
10+
* - [2, 2] -> [2, 2, 3] -> X
11+
* - [2] -> [2, 3] -> [2, 3, 3] -> X
12+
* - [3] -> [3, 3] -> OK
13+
* - ์ค‘๊ฐ„์— sum > target, sum == target ์ธ ๊ฒฝ์šฐ return ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ชจ๋“  ์ผ€์ด์Šค๋ฅผ ๋‹ค ๊ฒ€์‚ฌํ•˜์ง„ ์•Š์ง€๋งŒ
14+
* - ๊ธฐ๋ณธ์ ์œผ๋กœ ์•„๋ž˜์™€ ๊ฐ™์ด ๋ฌธ์ œ๋ฅผ ํ’€๊ฒŒ ๋  ๊ฒฝ์šฐ ์ตœ์•…์˜ ๊ฒฝ์šฐ์—๋Š” O(n^t) ๋งŒํผ ์†Œ์š”๋œ๋‹ค.
15+
*
16+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(t)
17+
* - t: target / candidates์˜ ์ตœ์†Ÿ๊ฐ’
18+
* - ์ด๊ฒƒ๋„ ์ƒ๊ฐํ•ด๋ณด๋‹ˆ๊นŒ ์ฃผ์–ด์ง„ candidates.length (=n) ๊ฐ’์— ๋น„๋ก€ํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ
19+
* - (๊ฐ€๋Šฅํ•œ ์ผ€์ด์Šค์—์„œ) ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์œผ๋กœ ํƒ€๊ฒŸ์„ ์ฑ„์šฐ๋Š” ๊ฒŒ ๊ฐ€์žฅ ๋งŽ์€ ์‚ฌ์ด์ฆˆ๋ฅผ ์ฐจ์ง€ํ•˜๋Š” ๊ฐ’์ด ๋ ํ…๋ฐ, ์ด๊ฒƒ์— ์˜ํ–ฅ์„ ๋ฐ›๊ฒ ๊ตฐ.
20+
*
21+
*/
22+
class Solution {
23+
24+
private List<List<Integer>> answer = new ArrayList<>();
25+
private List<Integer> combination = new ArrayList<>();
26+
27+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
28+
backtracking(candidates, target, 0, 0);
29+
return answer;
30+
}
31+
32+
private void backtracking(int[] candidates, int target, int sum, int start) {
33+
if (sum > target) {
34+
return;
35+
}
36+
if (sum == target) {
37+
answer.add(new ArrayList<>(combination));
38+
return;
39+
}
40+
for (int i = start; i < candidates.length; i++) {
41+
combination.add(candidates[i]);
42+
backtracking(candidates, target, sum + candidates[i], i);
43+
combination.remove(combination.size() - 1);
44+
}
45+
}
46+
}

0 commit comments

Comments
ย (0)