Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C Where the candidate numbers sums to T.
The same repeated number is chosen from C unlimited number of times.
Note:
- All numbers (including target) would be positive integers.
- Elements in a combination (a1, a 2, ..., aK) must is in non-descending order. (ie, a1≤ a2≤ ... ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set and 2,3,6,7
target 7
,
A Solution set is:
[7]
[2, 2, 3]
Problem Solving Ideas:
First of all, the topic of the bug, the actual test in C elements will not be duplicated, and therefore reduced a lot of difficulty, the simplest implementation method, DFS algorithm, Java implementation is as follows:
static public list<list<integer>> combinationsum (int[] candidates,int target) {List<list<integer >> list = new arraylist<list<integer>> (); Arrays.sort (candidates);d FS (list, candidates, 0, target, 0); return list;} static list<integer> List2 = new arraylist<integer> (); static void Dfs (List<list<integer>> List , int[] array, int result,int target, int depth) {if (result = = target) {list.add (new arraylist<integer> (List2)); RET Urn;} else if (depth >= array.length | | result > Target) return;for (int i = 0; I <= target/array[depth]; i++) {for (i NT J = 0; J < I; J + +) List2.add (array[depth]);d FS (list, array, result + array[depth] * I, Target, depth+1); for (int j = 0; J < i; j + +) Lis T2.remove (List2.size ()-1);}}
Java for Leetcode 039 combination Sum