|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=39 lang=java |
| 3 | + * |
| 4 | + * [39] Combination Sum |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/combination-sum/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (50.27%) |
| 10 | + * Likes: 2327 |
| 11 | + * Dislikes: 72 |
| 12 | + * Total Accepted: 384.4K |
| 13 | + * Total Submissions: 763.7K |
| 14 | + * Testcase Example: '[2,3,6,7]\n7' |
| 15 | + * |
| 16 | + * Given a set of candidate numbers (candidates) (without duplicates) and a |
| 17 | + * target number (target), find all unique combinations in candidates where the |
| 18 | + * candidate numbers sums to target. |
| 19 | + * |
| 20 | + * The same repeated number may be chosen from candidates unlimited number of |
| 21 | + * times. |
| 22 | + * |
| 23 | + * Note: |
| 24 | + * |
| 25 | + * |
| 26 | + * All numbers (including target) will be positive integers. |
| 27 | + * The solution set must not contain duplicate combinations. |
| 28 | + * |
| 29 | + * |
| 30 | + * Example 1: |
| 31 | + * |
| 32 | + * |
| 33 | + * Input: candidates = [2,3,6,7], target = 7, |
| 34 | + * A solution set is: |
| 35 | + * [ |
| 36 | + * [7], |
| 37 | + * [2,2,3] |
| 38 | + * ] |
| 39 | + * |
| 40 | + * |
| 41 | + * Example 2: |
| 42 | + * |
| 43 | + * |
| 44 | + * Input: candidates = [2,3,5], target = 8, |
| 45 | + * A solution set is: |
| 46 | + * [ |
| 47 | + * [2,2,2,2], |
| 48 | + * [2,3,3], |
| 49 | + * [3,5] |
| 50 | + * ] |
| 51 | + * |
| 52 | + * |
| 53 | + */ |
| 54 | +class Solution { |
| 55 | + public List<List<Integer>> combinationSum(int[] candidates, int target) { |
| 56 | + List<List<Integer>> list = new ArrayList<>(); |
| 57 | + backtrace(list, new ArrayList<Integer>(), candidates, target, 0); |
| 58 | + return list; |
| 59 | + } |
| 60 | + |
| 61 | + public void backtrace(List<List<Integer>> list, List<Integer> track, int[] candidates, int remain, int start) { |
| 62 | + if (remain < 0) return; |
| 63 | + if (remain == 0) { |
| 64 | + list.add(new ArrayList<Integer>(track)); |
| 65 | + } else { |
| 66 | + for (int i = start; i < candidates.length; i++) { |
| 67 | + track.add(candidates[i]); |
| 68 | + backtrace(list, track, candidates, remain - candidates[i], i); |
| 69 | + track.remove(track.size() - 1); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments