【发布时间】:2016-06-02 16:22:21
【问题描述】:
我的代码将生成candidates 中值的所有组合(包括重复),以便这些值汇总为目标。这是我对https://leetcode.com/problems/combination-sum/ 的解决方案。
我有点困惑为什么我需要包含以下代码行:
currentSet = new ArrayList<>(currentSet);
这实际上使 currentSet 成为所有递归调用的私有变量。否则,currentSet 将是一个共享变量,递归调用将同时修改该变量,从而导致问题。例如,当上面的语句从代码中省略时,
combinationSum({1, 2}, 4) 有以下输出:
[[1, 1, 2], [1, 1, 1, 1], [1, 2]]
数组 [1,2] 显然不等于 4。任何人都可以提供一个可靠的解释为什么会发生这种情况吗?
此外,我是否可以进行任何优化,以便我的代码可以避免放入重复但重新排序的数组,因为我当前的蛮力排序和检查是否包含在 HashSet 中的方法会导致非常糟糕的复杂性。
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Set<List<Integer>> returnSet = new HashSet<>();
returnSet = combSum(candidates, target, 0, returnSet, new ArrayList<Integer>());
return new ArrayList<>(returnSet);
}
private Set<List<Integer>> combSum(int[] candidates, int target, int i, Set<List<Integer>> returnSet,
List<Integer> currentSet) {
currentSet = new ArrayList<>(currentSet);
if(i == target) {
Collections.sort(currentSet);
if(!returnSet.contains(currentSet)) {
returnSet.add(new ArrayList<Integer>(currentSet));
}
} else if(i <= target){
System.out.println("Current set: " + returnSet.toString());
System.out.println("Current sum: " + i + " current target: " + target);
for(int a: candidates) {
if(i + a <= target) {
System.out.println("\tAdding: " + a + " so that the new sum will be: " + (i + a));
currentSet.add(a);
returnSet = combSum(candidates, target, i + a, returnSet, currentSet);
currentSet.remove(currentSet.size() - 1);
}
}
}
return returnSet;
}
【问题讨论】: