|
| 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