You are modifying a list as you are iterating thru it. A couple of issues here.
- don't use streams. It isn't appropriate or helpful.
- make a copy of
powerSet
and the added list per cycle to avoid a CME.
List<Integer> list = new ArrayList<>(List.of(20,30,40,50));
List<List<Integer>> ret = powerSet(list);
ret.forEach(System.out::println);
Prints
[]
[20]
[30]
[20, 30]
[40]
[20, 40]
[30, 40]
[20, 30, 40]
[50]
[20, 50]
[30, 50]
[20, 30, 50]
[40, 50]
[20, 40, 50]
[30, 40, 50]
[20, 30, 40, 50]
The modified methods.
public static List<List<Integer>> powerSet(List<Integer> arr) {
List<List<Integer>> powerSet = new ArrayList<>();
powerSet.add(new ArrayList<>());
if (arr.size() <= 0)
return powerSet;
for (Integer elem:arr) {
for (List<Integer> lst : powerSet) { // <-- instead of streams.
powerSet = new ArrayList<>(powerSet); // <-- new copy here
addSubset(powerSet, lst, elem);
}
}
return powerSet;
}
public static void addSubset(
List<List<Integer>> powerSet, List<Integer> p, int elem) {
p = new ArrayList<>(p); // <-- new copy here
p.add(elem);
powerSet.add(p);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…