leetcode : combination sum II
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.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(candidates == null || candidates.length == 0) {
return result;
}
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(candidates);
helper(result, list, candidates, 0, target);
return result;
}
public void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int position, int remain) {
if(remain < 0) {
return;
}
if(remain == 0) {
result.add(new ArrayList<Integer>(list));
}
for(int i = position; i < nums.length; i++) {
if(i > position && nums[i] == nums[i - 1]) {
continue;
}
list.add(nums[i]);
helper(result, list, nums, i + 1, remain - nums[i]);
list.remove(list.size() - 1);
}
}
}
浙公网安备 33010602011771号