Given A collection of candidate numbers (C) and a target number (T), find all unique combinations in c where the candidate numbers sums to T.
Each number in C is used once in the combination.
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 10,1,2,7,6,1,5
target 8
,
A Solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Problem Solving Ideas:
Modify the title code, set the DFS width to 2, note that using set, prevent duplication, Java implementation is as follows:
Public list<list<integer>> combinationSum2 (int[] candidates, int target) {set<list<integer>> List = new hashset<list<integer>> (); Arrays.sort (candidates);d FS (list, candidates, 0, target, 0); return new arraylist<list<integer>> (list);} static list<integer> List2 = new arraylist<integer> (); static void Dfs (Set<list<integer>> List, int[] array, int result,int target, int depth) {if (result = = target) {list.add (new arraylist<integer> (List2)); retur n;} else if (depth >= array.length | | result > Target) return;for (int i = 0; I <= 1; i++) {for (int 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);}}
Results 453 MS, the efficiency is slightly lower, so replace set, with a variable to calculate the width of each DFS, Java implementation is as follows:
Public list<list<integer>> combinationSum2 (int[] candidates, int target) {Arraylist<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 (arraylist<list<integer> > list, int[] array, int result,int target, int depth) {if (result = = target) {list.add (new arraylist<integer> (Li ST2)); return;} else if (depth >= array.length | | result > Target) return;int step=1;while (depth<array.length-1&&array[ Depth]==array[depth+1]) {depth++;step++;} for (int i = 0; I <= step; i++) {for (int 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 + +) List2.remove (List2.size ()-1);}}
Java for Leetcode 040 combination Sum II