如何生成List< List< String>>的所有排列? [英] How to generate all permutations of a List<List<String>>?

查看:115
本文介绍了如何生成List< List< String>>的所有排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成List<List<String>>的所有排列,但是我没有获得唯一的排列.

I am trying to generate all permutations of a List<List<String>> but I am not getting unique permutations.

我的List<List<String>>看起来像

[
 [Test, Test 1, Test 2],
 [Apple, Sandwich, Banana],
 [Cake, Ice Cream, Fruit]
] 

我正在尝试获取父级List<String>中每个List<String的所有组合.因此,例如,第一个实例应具有:

I am trying to get every combination possible for each List<String within the parent List<String>. So, for example, the first instance should have:

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test, Test 2]
[Test 1, Test 2, Test]

现在,我的尝试将只是迭代并重复元素,而不会更改顺序,因此对于父级List<String>的大小,将仅重复[Test, Test 1, Test 2].这是我的方法.任何帮助表示赞赏:

Right now, my attempt will just iterate and repeat the elements without changing the order so [Test, Test 1, Test 2] will just be repeated for the size of the parent List<String>. This is my approach. Any help is appreciated:

List<List<String>> allPerms = parentList.stream().map(line -> parentList.stream()).flatMap(l -> l.filter(j -> !j.equals(l))).collect(Collectors.toList());

推荐答案

使用或回溯

public static void permute(List<String> list, int left, int right) {
    if (left == right) {
        System.out.println(Arrays.toString(list.toArray()));
        return;
    }
    for (int j = left; j <= right; j++) {
        Collections.swap(list, left, j);
        permute(list, left + 1, right);
        Collections.swap(list, left, j);
    }
}

public static void showAllPermute(List<String> list) {
    int size = list.size();
    permute(list, 0, size - 1);
}

测试

List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("Test", "Test 1", "Test 2"));
list.add(Arrays.asList("Apple", "Sandwich", "Banana"));
list.add(Arrays.asList("Cake", "Ice Cream", "Fruit"));

// list.forEach(t -> showAllPermuteByCommons(t));
list.forEach(t -> showAllPermute(t));

输出

[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test 2, Test]
[Test 1, Test, Test 2]
[Apple, Sandwich, Banana]
[Apple, Banana, Sandwich]
[Banana, Apple, Sandwich]
[Banana, Sandwich, Apple]
[Sandwich, Banana, Apple]
[Sandwich, Apple, Banana]
[Cake, Ice Cream, Fruit]
[Cake, Fruit, Ice Cream]
[Fruit, Cake, Ice Cream]
[Fruit, Ice Cream, Cake]
[Ice Cream, Fruit, Cake]
[Ice Cream, Cake, Fruit]

这篇关于如何生成List&lt; List&lt; String&gt;&gt;的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆