【发布时间】:2018-03-29 04:13:35
【问题描述】:
这样,[2,2,3] & [2,3,2] 两者都不应该出现在其中。
我在代码中所做的是给定一个集合 [2, 3, 6, 7] 和目标 7,我发现候选数字总和为目标的唯一组合
输出:
[
[7],
[2, 2, 3]
]
代码运行良好,但我觉得我通过创建HashSet<ArrayList<Integer>> 使用了一种复杂的方式,使用 Collection.sort() 来避免重复列表。有没有更好的方法可以避免这种情况?
HashSet<ArrayList<Integer>> set= new HashSet<ArrayList<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtract(candidates,target,0, new ArrayList<Integer>(),0);
List<List<Integer>> output=new ArrayList<List<Integer>>(set);
return output;
}
public void backtract(int[] candidates, int target, int pos, List<Integer> list, int sum){
if(sum==target){
ArrayList l=new ArrayList<Integer>(list);
Collections.sort(l);
set.add(l);
}
for(int i=0;i<candidates.length;i++){
if(sum+candidates[i] > target){
continue;
}
sum=sum+candidates[i];
list.add(candidates[i]);
backtract(candidates,target,i+1, list,sum);
list.remove(new Integer(candidates[i]));
sum=sum-candidates[i];
}
}
【问题讨论】:
-
使用
List<List<Set>>,没什么复杂的,不会添加重复项。 -
尝试类似子集总和算法
标签: java list sorting arraylist set