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 47 48 49 50 51 52 53 54 55
| import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.ArrayList;
public class CombinationSum2 {
public List<List<Integer>> combinationSum2(int[] num, int target) { // handle edge case if (num.length == 0 || target <= 0) return null;
// sort the array Arrays.sort(num);
List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> current = new ArrayList<Integer>();
getResult(num, target, result, current, -1);
return new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(result)); }
private void getResult(int[] num, int target, List<List<Integer>> result, List<Integer> current, int start) { if (target == 0) { List<Integer> tmp = new ArrayList<Integer>(current); result.add(tmp); return; } else { for (int i = start + 1; i < num.length; i++) { int offset = target - num[i]; if(offset < 0) { return; } current.add(num[i]); getResult(num, offset, result, current, i); current.remove(current.size()-1); }
} }
public static void main(String[] args) { int[] num = new int[]{10,1,2,7,6,1,5}; List<List<Integer>> result = new CombinationSum2().combinationSum2(num, 8); for(List<Integer> i : result) { System.out.print("["); for(int j : i) { System.out.print(j + " "); } System.out.println("]"); }
} }
|