在不同长度的列表中查找所有可能的元素组合

时间:2014-09-17 05:31:46

标签: java combinations permutation

我有n个列表,每个列表都有可变数量的元素。我想在列表中找到所有可能的元素组合。

例如,

list1 = l11, l12  
list2 = l21  
list3 = l31,l32  

结果列表应包含

    [l11]  
    [l12]  
    [l21]  
    [l31]  
    [l32]  
    [l11, l21]  
    [l12, l21]  
    [l21, l31]  
    [l21, l32]  
    [l11, l31]  
    [l11, l32]
    [l12, l31]
    [l12, l32]  
    [l11, l21, l31]  
    [l11, l21, l32]  
    [l12, l21, l31]  
    [l12, l21, l31]  

请提供解决问题的一些见解。我正在java中实现解决方案

1 个答案:

答案 0 :(得分:1)

这种递归背后的想法是制作n-1个列表的所有子列表,然后将第一个列表中的每个元素添加到每个列表中,同时保持元素也可以从集合中丢失(保持完整的n- 1解决方案并添加新的可能集)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Combinations {

    public static void main(String[] args) {
        List<String> l1 = Arrays.asList("l11", "l12");
        List<String> l2 = Arrays.asList("l21");
        List<String> l3 = Arrays.asList("l31", "l32");
        List<List<String>> lists = Arrays.asList(l1, l2, l3);
        List<List<String>> allSubsets = allSubsets(lists);
        for (List<String> subset : allSubsets) {
            System.out.println(subset);
        }
    }

    static List<List<String>> allSubsets(List<List<String>> lists) {
        if (lists.isEmpty()) {
            List<String> empty = new ArrayList<>();
            return Arrays.asList(empty);
        }

        List<List<String>> reduced = new ArrayList<>();
        reduced.addAll(lists);
        List<String> list = reduced.remove(0);
        List<List<String>> subsets = allSubsets(reduced);
        List<List<String>> newSubsets = new ArrayList<>(subsets);
        for (List<String> subset : subsets) {
            for (String s : list) {
                List<String> newSubset = new ArrayList<>(subset);
                newSubset.add(s);
                newSubsets.add(newSubset);
            }
        }
        return newSubsets;
    }
}