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 may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
10,1,2,7,6,1,5
and target 8
, A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.combinations; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
/** | |
* Almost same as CombinationSum I, Only difference is element can only used in combination once. | |
* As there're duplicate elements, we need to make sure result with no duplidates like subsets II. | |
* | |
* Element used once --> helper(xxx, i+1) | |
* Result without duplicates --> if(i!=position && num[i] == nums[i-1]) { continue; } | |
* | |
* i!=position --> only happens when backtrack, after move number1. number2 cannot be used. | |
* i==position --> just add number2, not iterative it. (We don't allow number2 iteration which number1 already does) | |
* | |
* @author jeffwan | |
* @date Feb 11, 2014 | |
*/ | |
public class CombinationSum2 { | |
public static void main(String[] args) { | |
int[] nums = {10, 1, 2, 7, 6, 1, 5}; | |
int target = 8; | |
System.out.println(combinationSum2(nums,target)); | |
} | |
public static ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { | |
Arrays.sort(num); | |
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); | |
ArrayList<Integer> list = new ArrayList<Integer>(); | |
combinationSumHelper(result, list, num, target, 0); | |
return result; | |
} | |
private static void combinationSumHelper(ArrayList<ArrayList<Integer>> result, | |
ArrayList<Integer> list, int[] num, int target, int position) { | |
int sum = 0; | |
for (int x: list) { | |
sum += x; | |
} | |
if (sum == target) { | |
result.add(new ArrayList<Integer>(list)); | |
return; | |
} | |
if (sum < target) { | |
for (int i = position; i<num.length; i++) { | |
if ( i != position && num[i] == num[i-1]) { | |
continue; | |
} | |
list.add(num[i]); | |
combinationSumHelper(result, list, num, target, i+1); | |
list.remove(list.size() - 1); | |
} | |
} | |
} | |
} |
No comments:
Post a Comment