题目描述(传送门)
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]
解题思路&代码实现
【回溯算法】leetcode90.子集II
之前我们做过子集II,这个刚好也是无重复元素的,只要再把选出来的结果进行判断,将和等于target的返回即可。
问题来了,这样时间复杂度是肯定过不了!!!
分析
思路(剪枝)
代码
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<Integer> list = new ArrayList<>();
List<List<Integer>> listList = new ArrayList<>();
Set<List<Integer>> set = new HashSet<>();
Arrays.sort(candidates);
int sum = 0;
combinationSum2Helper(0, target, candidates, sum,list, listList, set);
return listList;
}
private void combinationSum2Helper(int i, int target, int[] candidates, int sum, List<Integer> list, List<List<Integer>> listList, Set<List<Integer>> set) {
if (i >= candidates.length || sum > target) {
return;
}
list.add(candidates[i]);
sum += candidates[i];
if (!set.contains(list) && sum == target) {
set.add(new ArrayList<>(list));
listList.add(new ArrayList<>(list));
}
combinationSum2Helper(i + 1, target, candidates, sum, list, listList, set);
list.remove(list.size()-1);
sum -= candidates[i];
combinationSum2Helper(i + 1, target, candidates, sum, list, listList, set);
}
}
问题来了!!!
都通过了,但是还是超时!!!
C++到是过了。这个问题保留后边再看。我想可能是Set.contains