|
| 1 | +import java.util.ArrayList; |
| 2 | + |
| 3 | + |
| 4 | +/* |
| 5 | +Given a set of candidate numbers (C) and a target number (T), |
| 6 | +find all unique combinations in C where the candidate numbers sums to T. |
| 7 | +
|
| 8 | +The same repeated number may be chosen from C unlimited number of times. |
| 9 | +
|
| 10 | +Note: |
| 11 | +All numbers (including target) will be positive integers. |
| 12 | +Elements in a combination (a1, a2, … ,ak) |
| 13 | +must be in non-descending order. (ie, a1 ? a2 ? … ? ak). |
| 14 | +The solution set must not contain duplicate combinations. |
| 15 | +For example, given candidate set 2,3,6,7 and target 7, |
| 16 | +A solution set is: |
| 17 | +[7] |
| 18 | +[2, 2, 3] |
| 19 | +*/ |
| 20 | +public class CombinationSum { |
| 21 | + public static void main(String[] args){ |
| 22 | + int[] a = new int[]{2,3,6,7,10}; |
| 23 | + int target = 10; |
| 24 | + |
| 25 | + ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); |
| 26 | + ArrayList<Integer> r = new ArrayList<Integer>(); |
| 27 | + combinationSum(a, 0, target, r, results); |
| 28 | + |
| 29 | + System.out.println(results.toString()); |
| 30 | + |
| 31 | + } |
| 32 | + public static void combinationSum(int[] a, |
| 33 | + int index, |
| 34 | + int target, |
| 35 | + ArrayList<Integer> r, |
| 36 | + ArrayList<ArrayList<Integer>> results){ |
| 37 | + |
| 38 | + |
| 39 | + if(target ==0){ |
| 40 | + results.add(new ArrayList<Integer>(r)); |
| 41 | + return; |
| 42 | + } |
| 43 | + if(a.length == index) |
| 44 | + return; |
| 45 | + |
| 46 | + combinationSum(a,index+1,target,r, results); |
| 47 | + |
| 48 | + int tmp = a[index]; |
| 49 | + int canUse = target/tmp; |
| 50 | + for(int i=1; i<= canUse; ++i){ |
| 51 | + r.add(tmp); |
| 52 | + combinationSum(a, index+1, target-tmp*i,r, results); |
| 53 | + } |
| 54 | + |
| 55 | + for(int i=1; i<= canUse; ++i){ |
| 56 | + r.remove(Integer.valueOf(tmp)); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments