Title Description:
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:
Similar to the previous one, but each time the current element is selected, the element of the next position is selected directly. And before each element is selected, it is ensured that the element is not coincident with the last element.
The code is as follows:
public class Solution {public list<list<integer>> combinationSum2 (int[] candidates,int target) { Arrays.sort (candidates); list<list<integer>> result = new arraylist<list<integer>> (); GetResult (result, new ArrayList <Integer> (), candidates, target, 0); return result;} public void GetResult (list<list<integer>> result,list<integer> Current, int[] candiates, int target, int start) {if (Target > 0) {for (int i = start; I < candiates.length && target >= candiates[i]; i++) {if (i > Start && candiates[i] = = Candiates[i-1]) continue;current.add (Candiates[i]); GetResult (result, current, Candiates, Target-candiates[i],i + 1); Current.remove (Current.size ()-1);}} else if (target = = 0) {result.add (new arraylist<integer> (current));}}}
Java [Leetcode 40]combination Sum II