Java : Cartesian Product of a List of Lists

后端 未结 12 1090
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 19:03

I have a problem that is really kind of a general programming question, but my implementation is in Java, so I will provide my examples that way

I have a class like

12条回答
  •  生来不讨喜
    2020-12-02 19:49

    Recursive solution:

    public  List> cartesianProduct(int i, List... a) {
        if(i == a.length ) {
            List> result = new ArrayList<>();
            result.add(new ArrayList());
            return result;
        }
        List> next = cartesianProduct(i+1, a);
        List> result = new ArrayList<>();
        for(int j=0; j < a[i].size(); j++) {
            for(int k=0; k < next.size(); k++) {
                List concat = new ArrayList();
                concat.add(a[i].get(j));
                concat.addAll(next.get(k));
                result.add(concat);
            }
        }
        return result;
    }
    

提交回复
热议问题