-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy patheunhwa99.java
32 lines (27 loc) ยท 1.42 KB
/
eunhwa99.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.ArrayList;
import java.util.List;
// backtracking
// ์๊ฐ๋ณต์ก๋: ๊ฐ ๋ฐฐ์ด ์์๋ง๋ค target์ ๋ง๋๋ ๋ฐ์ ๊ธฐ์ฌ๋ฅผ ํ ์๋ ์๊ณ ์ ํ ์๋ ์์ -> O(2^(target))
// ๊ณต๊ฐ๋ณต์ก๋: O(k * t) (k๋ ๊ฐ๋ฅํ ์กฐํฉ์ ์, t๋ ๊ฐ ์กฐํฉ์ ํฌ๊ธฐ)
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, target, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] candidates, int target, int start, List<Integer> currentCombination, List<List<Integer>> result) {
// ๋ชฉํ๊ฐ์ ๋๋ฌํ๋ฉด ํ์ฌ ์กฐํฉ์ ๊ฒฐ๊ณผ์ ์ถ๊ฐ
if (target == 0) {
result.add(new ArrayList<>(currentCombination));
return;
}
// ํ๋ณด ์ซ์๋ค์ ํ์
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > target) continue; // ๋ชฉํ๊ฐ๋ณด๋ค ํฐ ์ซ์๋ ๋์ด๊ฐ
currentCombination.add(candidates[i]); // ํ์ฌ ์ซ์๋ฅผ ์ ํ
// ํ์ฌ ์ซ์๋ฅผ ๋ค์ ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ i๋ฅผ ๊ทธ๋๋ก ๋๊ณ ์ฌ๊ท ํธ์ถ
backtrack(candidates, target - candidates[i], i, currentCombination, result);
currentCombination.remove(currentCombination.size() - 1); // ๋ฐฑํธ๋ํน: ๋ง์ง๋ง ์ซ์ ์ ๊ฑฐ
}
}
}