如何避免List <list <integer>&gt;中的重复列表在java中

时间:2018-03-29 04:13:36

标签: java list sorting arraylist set

这样,[2,2,3]&amp; [2,3,2]两者都不应该出现在其中。

我在代码中做的是给出一组[2,3,6,7]和目标7,我发现候选数字总和为目标的唯一组合

输出:

[

[7],

[2,2,3]

] 代码工作正常但我觉得我使用复杂的方法创建{ awaiting_status: false, batch: 1, email_exists: true, receipts: ["test1", "test2"] } ,使用Collection.sort()来避免重复列表。有没有更好的方法可以避免这种情况?

HashSet<ArrayList<Integer>>

1 个答案:

答案 0 :(得分:0)

这是一种可能的方式。

public static void backtract(int[] candidates, int target, int pos, List<Integer> list, int sum) {
    if(sum == target){
        finalOutput.add(new ArrayList<Integer>(list));
        return;
    }

    for (int i = pos; i < candidates.length; i++) {
        for (int j = 1; j <= (target - sum) / candidates[i]; j++) {
            List<Integer> newList = new ArrayList<>(list);
            for (int k = 0; k < j; k++) {
                newList.add(candidates[i]);
            }
            backtract(candidates, target, i + 1, newList, sum + (candidates[i] * j));
        }
    }
}

此问题的主要挑战是允许多次拾取特定元素。

因此,(在上面的代码中)的想法是继续在每个递归调用上前进。在您的代码中,每个递归调用都从索引0处的元素开始,这是导致重复的原因。这里,每个递归调用都从索引pos的元素开始。

要多次选择一个特定元素,我们通过选中(target - sum) / candidates[i](让它为ct来检查它中有多少(当前元素)可以对整个(剩余)目标做出贡献。因此,我们通过选择 1,2,3 ... ct 进行递归调用(添加到当前总和)。

有些观点:

  1. 为避免改变数组,我创建了新的数组来简化代码。如果证明它会影响性能,您可以更改它。
  2. 我将finalOutput保留为静态变量。您可以将其作为参数传递。