|
| 1 | +packagecom.hadley; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | +importjava.util.Arrays; |
| 5 | +importjava.util.List; |
| 6 | + |
| 7 | +/* |
| 8 | +2020.05.07 |
| 9 | +Given a collection of candidate numbers (candidates) and a target number (target), |
| 10 | +find all unique combinations in candidates where the candidate numbers sums to target. |
| 11 | +
|
| 12 | +Each number in candidates may only be used once in the combination. |
| 13 | +
|
| 14 | +Note: |
| 15 | +
|
| 16 | +All numbers (including target) will be positive integers. |
| 17 | +The solution set must not contain duplicate combinations. |
| 18 | +Example 1: |
| 19 | +
|
| 20 | +Input: candidates = [10,1,2,7,6,1,5], target = 8, |
| 21 | +A solution set is: |
| 22 | +[ |
| 23 | + [1, 7], |
| 24 | + [1, 2, 5], |
| 25 | + [2, 6], |
| 26 | + [1, 1, 6] |
| 27 | +] |
| 28 | +Example 2: |
| 29 | +
|
| 30 | +Input: candidates = [2,5,2,1,2], target = 5, |
| 31 | +A solution set is: |
| 32 | +[ |
| 33 | + [1,2,2], |
| 34 | + [5] |
| 35 | +] |
| 36 | + */ |
| 37 | +publicclass_040 { |
| 38 | + |
| 39 | +publicList<List<Integer>>combinationSum2(int[]candidates,inttarget) { |
| 40 | +List<List<Integer>>ans =newArrayList<>(); |
| 41 | +Arrays.sort(candidates); |
| 42 | +dfs(candidates,target,0,newArrayList<Integer>(),ans); |
| 43 | + |
| 44 | +returnans; |
| 45 | + } |
| 46 | + |
| 47 | +/* |
| 48 | + curList = current operating List |
| 49 | + */ |
| 50 | +publicvoiddfs(int[]candidates,inttarget,intindex,List<Integer>curList,List<List<Integer>>ans){ |
| 51 | +if(target ==0){ |
| 52 | +ans.add(newArrayList<>(curList)); |
| 53 | +return; |
| 54 | + } |
| 55 | + |
| 56 | +for(inti =index;i <candidates.length;i++){ |
| 57 | +if(candidates[i] >target){ |
| 58 | +break; |
| 59 | + } |
| 60 | + |
| 61 | +//skip the same element |
| 62 | +if(i >index &&candidates[i] ==candidates[i-1]){ |
| 63 | +continue; |
| 64 | + } |
| 65 | +curList.add(candidates[i]); |
| 66 | +dfs(candidates,target -candidates[i],i +1,curList,ans); |
| 67 | +curList.remove(curList.size()-1); |
| 68 | + } |
| 69 | + |
| 70 | + } |
| 71 | +} |