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]
]
Solution:Backtracking
总结见:http://www.jianshu.com/p/883fdda93a66
思路:
和39题 Combination Sum http://www.jianshu.com/p/65dbdddcd398 思路相同,加上 if(i > start && nums[i] == nums[i - 1]) continue; to skip duplicates (sort 是必需的)
Time Complexity: O(2^N) Space Complexity: O(N)
Solution Code:
class Solution {
public List<List<Integer>> combinationSum2(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> cur_res = new ArrayList<>();
Arrays.sort(nums);
backtrack(nums, 0, target, cur_res, result);
return result;
}
private void backtrack(int[] nums, int start, int remain, List<Integer> cur_res, List<List<Integer>> result) {
if(remain < 0) return; // early stop
else if(remain == 0) {
result.add(new ArrayList<>(cur_res));
}
else{
for(int i = start; i < nums.length; i++){
if(i > start && nums[i] == nums[i - 1]) continue; // skip duplicates
cur_res.add(nums[i]);
backtrack(nums, i + 1, remain - nums[i], cur_res, result);
cur_res.remove(cur_res.size() - 1);
}
}
}
}