-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathtaekwon-dev.java
46 lines (43 loc) ยท 1.8 KB
/
taekwon-dev.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* ์๊ณ ๋ฆฌ์ฆ: ๋ฐฑํธ๋ํน
* ์๊ฐ ๋ณต์ก๋: O(n^t)
* - n: candidates.lenth
* - t: target / candidates์ ์ต์๊ฐ
* - ์์๋ฅผ ํตํด ์๊ฐ ๋ณต์ก๋๋ฅผ ์ดํดํด๋ณด์!
*
* - candidates: [2, 3], target: 6
* - [2] -> [2, 2] -> [2, 2, 2] -> OK (์ฌ๊ธฐ์ ์๊ฐํด๋ณด๋ฉด, ์ ์ฌ๊ท๋ฅผ ์ต๋ 6/2 ๋งํผ ํ๊ณ ๋ค์ด๊ฐ๊ฒ ๊ตฐ?)
* - [2, 2] -> [2, 2, 3] -> X
* - [2] -> [2, 3] -> [2, 3, 3] -> X
* - [3] -> [3, 3] -> OK
* - ์ค๊ฐ์ sum > target, sum == target ์ธ ๊ฒฝ์ฐ return ํ๊ธฐ ๋๋ฌธ์ ๋ชจ๋ ์ผ์ด์ค๋ฅผ ๋ค ๊ฒ์ฌํ์ง ์์ง๋ง
* - ๊ธฐ๋ณธ์ ์ผ๋ก ์๋์ ๊ฐ์ด ๋ฌธ์ ๋ฅผ ํ๊ฒ ๋ ๊ฒฝ์ฐ ์ต์
์ ๊ฒฝ์ฐ์๋ O(n^t) ๋งํผ ์์๋๋ค.
*
* ๊ณต๊ฐ ๋ณต์ก๋: O(t)
* - t: target / candidates์ ์ต์๊ฐ
* - ์ด๊ฒ๋ ์๊ฐํด๋ณด๋๊น ์ฃผ์ด์ง candidates.length (=n) ๊ฐ์ ๋น๋กํ๋ ๊ฒ ์๋๋ผ
* - (๊ฐ๋ฅํ ์ผ์ด์ค์์) ๊ฐ์ฅ ์์ ๊ฐ์ผ๋ก ํ๊ฒ์ ์ฑ์ฐ๋ ๊ฒ ๊ฐ์ฅ ๋ง์ ์ฌ์ด์ฆ๋ฅผ ์ฐจ์งํ๋ ๊ฐ์ด ๋ ํ
๋ฐ, ์ด๊ฒ์ ์ํฅ์ ๋ฐ๊ฒ ๊ตฐ.
*
*/
class Solution {
private List<List<Integer>> answer = new ArrayList<>();
private List<Integer> combination = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(candidates, target, 0, 0);
return answer;
}
private void backtracking(int[] candidates, int target, int sum, int start) {
if (sum > target) {
return;
}
if (sum == target) {
answer.add(new ArrayList<>(combination));
return;
}
for (int i = start; i < candidates.length; i++) {
combination.add(candidates[i]);
backtracking(candidates, target, sum + candidates[i], i);
combination.remove(combination.size() - 1);
}
}
}