我試圖消除在返回列表複製在this questionC++中的一組列表
鑑於候選人編號(C)和目標數(T)的集合中刪除重複,發現在所有的獨特組合C,其中候選號碼總和爲T.
C中的每個數字只能在組合中使用一次。
注:
所有號碼(包括目標)將是正整數。
組合中的元素(a1,a2,...,ak)必須爲非降序。 (即a1≤a2≤...≤ak)。
該解決方案集不能包含重複的組合。
例如,給定候選集10,1,2,7,6,1,5和目標8, 的溶液組是:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
我的問題是如何有效地除去重複? 以下是我的代碼:
public class Solution {
public static void main(String[] args) {
int[] input = { 10, 1, 2, 7, 6, 1, 5 };
// int[] input = { 2, 1, 1, 4, 4, 2 };
System.out.println(combinationSum2(input, 8));
}
private static class Entry {
List<Integer> list;
int target;
int index; // the previous index
public Entry(int target) {
list = new LinkedList<Integer>();
this.target = target;
}
public int add(int num, int index) {
this.list.add(num);
this.index = index;
this.target -= num;
return target;
}
public Entry copy() {
Entry copy = new Entry(this.target);
copy.list = new ArrayList<>();
copy.list.addAll(list);
copy.target = target;
copy.index = index;
return copy;
}
}
public static List<List<Integer>> combinationSum2(int[] input, int target) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
if (null == input || input.length <= 0)
return ret;
Arrays.sort(input);
int N = input.length;
Queue<Entry> pool = new LinkedList<Entry>();
for (int i = 0; i < N; i++) {
if (input[i] <= target) {
Entry entry = new Entry(target);
entry.add(input[i], i);
pool.add(entry);
}
}
while (!pool.isEmpty()) {
Entry cur = pool.poll();
if (cur.target == 0) {
ret.add(cur.list);
} else if (cur.target > 0) {
for (int i = cur.index + 1; i < N; i++) {
if (cur.target - input[i] >= 0) {
Entry copy = cur.copy();
copy.add(input[i], i);
pool.offer(copy);
} else {
break;
}
}
}
}
return ret;
}
}
我的第一個想法是在返回列表中的列表進行排序,比較它們一個一個地刪除重複。但有沒有更快的方法?或任何建議?