|
| 1 | +package Algorithms; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +public class CombinationSum{ |
| 7 | + public ArrayList<ArrayList<Integer>> combine(int n, int k) { |
| 8 | + ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>(); |
| 9 | + |
| 10 | + help(n, 0, new ArrayList<Integer>(), rst, k); |
| 11 | + |
| 12 | + return rst; |
| 13 | + } |
| 14 | + |
| 15 | + public void help(int n, int index, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> rst, int k) { |
| 16 | + if (path.size() == k) { |
| 17 | + rst.add(new ArrayList<Integer>(path)); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + for (int i = index; i < n; i++) { |
| 22 | + path.add(i + 1); |
| 23 | + help(n, i + 1, path, rst, k); |
| 24 | + path.remove(path.size() - 1); |
| 25 | + } |
| 26 | + |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + CombinationSum cs = new CombinationSum(); |
| 33 | + |
| 34 | + int[] num = {1,2}; |
| 35 | + cs.combine(1, 1); |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + } |
| 42 | + |
| 43 | + public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) { |
| 44 | + ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>> (); |
| 45 | + Arrays.sort(candidates); |
| 46 | + |
| 47 | + help(candidates, 0, new ArrayList<Integer>(), rst, target); |
| 48 | + |
| 49 | + System.out.printf(rst.toString()); |
| 50 | + |
| 51 | + return rst; |
| 52 | + } |
| 53 | + |
| 54 | + public void help(int[] cand, int index, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> rst, int target) { |
| 55 | + if (target == 0) { |
| 56 | + // add the current set into the result. |
| 57 | + rst.add(new ArrayList<Integer>(path)); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + int pre = -1; |
| 62 | + for (int i = index; i < cand.length; i++) { |
| 63 | + if (cand[i] > target) { |
| 64 | + // because the sequence is ascending, so we don't need to go on. |
| 65 | + break; |
| 66 | + } |
| 67 | + |
| 68 | + if (cand[i] == pre) |
| 69 | + |
| 70 | + path.add(cand[i]); |
| 71 | + help(cand, index, path, rst, target - cand[i]); |
| 72 | + path.remove(path.size() - 1); |
| 73 | + } |
| 74 | + |
| 75 | + return; |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments