有没有办法找到一组共情的所有排列,但有些元素会相互排除

我试图在集合集合中找到排列,条件是每个内部集合中的元素只能出现一次。


例如,我有一个列表列表:[[a,b],[c,d],[e,f]],我的结果将是这样的:


[a]

[c]

[e]...

[a,c] ('a' appeared and excluded 'b')

[b,d]

[c,e]...

[a, c, e]

[b, d, f]

[a, c, f]

and so on...

或者至少帮我一些答案的链接 - 我是一个乞丐,仍然不知道使用搜索引擎提问所需的正确短语。


郎朗坤
浏览 121回答 1
1回答

HUX布斯

具有未排序输出的递归解决方案:public static <T> List<List<T>> permutations(List<List<T>> lists) {&nbsp; &nbsp; return permutations(lists, new ArrayList<>());}private static <T> List<List<T>> permutations(List<List<T>> lists, List<T> prefix) {&nbsp; &nbsp; if (lists.isEmpty()) return Arrays.asList(prefix);&nbsp; &nbsp; List<T> head = lists.get(0);&nbsp; &nbsp; List<List<T>> tail = lists.subList(1, lists.size());&nbsp; &nbsp; List<List<T>> result = new ArrayList<>();&nbsp; &nbsp; for (T t : head) {&nbsp; &nbsp; &nbsp; &nbsp; List<T> p = new ArrayList<>(prefix);&nbsp; &nbsp; &nbsp; &nbsp; p.add(t);&nbsp; &nbsp; &nbsp; &nbsp; result.addAll(permutations(tail, p));&nbsp; &nbsp; }&nbsp; &nbsp; result.addAll(permutations(tail, prefix));&nbsp; &nbsp; return result;}对于示例列表,输出为:[[a,b],[c,d],[e,f]][[a, c, e], [a, c, f], [a, c], [a, d, e], [a, d, f], [a, d], [a, e], [a, f], [a],&nbsp;[b, c, e], [b, c, f], [b, c], [b, d, e], [b, d, f], [b, d], [b, e], [b, f], [b],&nbsp;[c, e], [c, f], [c], [d, e], [d, f], [d], [e], [f], []]如果您需要按大小排序,则此速度大约慢2-3倍:public static <T> List<List<T>> permutations(List<List<T>> lists) {&nbsp; &nbsp; List<List<T>> result = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i <= lists.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; result.addAll(permutations(lists, i));&nbsp; &nbsp; }&nbsp; &nbsp; return result;}private static <T> List<List<T>> permutations(List<List<T>> lists, int count) {&nbsp; &nbsp; if (count == 0) return Arrays.asList(new ArrayList<>());&nbsp; &nbsp; List<List<T>> result = new ArrayList<>();&nbsp; &nbsp; for (int i = 0; i < lists.size() - count + 1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for (T t : lists.get(i)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (List<T> r : permutations(lists.subList(i + 1, lists.size()), count - 1)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r = new ArrayList<>(r);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r.add(0, t);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(r);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}输出:[[], [a], [b], [c], [d], [e], [f], [a, c], [a, d], [a, e], [a, f],&nbsp;[b, c], [b, d], [b, e], [b, f], [c, e], [c, f], [d, e], [d, f],&nbsp;[a, c, e], [a, c, f], [a, d, e], [a, d, f], [b, c, e], [b, c, f], [b, d, e], [b, d, f]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java