java实现笛卡尔积算法

private static void descartes(List> dimvalue, List> result, int layer, List curList) {
        if (layer < dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                descartes(dimvalue, result, layer + 1, curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List list = new ArrayList(curList);
                    list.add(dimvalue.get(layer).get(i));
                    descartes(dimvalue, result, layer + 1, list);
                }
            }
        } else if (layer == dimvalue.size() - 1) {
            if (dimvalue.get(layer).size() == 0) {
                result.add(curList);
            } else {
                for (int i = 0; i < dimvalue.get(layer).size(); i++) {
                    List list = new ArrayList(curList);
                    list.add(dimvalue.get(layer).get(i));
                    result.add(list);
                }
            }
        }
    }

public static void main(String[] args) {
            List> list = new ArrayList>();
            List listSub1 = new ArrayList();
            List listSub2 = new ArrayList();
            List listSub3 = new ArrayList();
            listSub1.add("1");
            listSub1.add("2");

            listSub2.add("3");
            listSub2.add("4");

            listSub3.add("a");
            listSub3.add("b");

            list.add(listSub1);
            list.add(listSub2);
            list.add(listSub3);
            List> result = new ArrayList>();
            descartes(list, result, 0, new ArrayList());
            System.out.println(JSON.toJSONString(result));

    } 
运行结果:
[["1","3","a"],["1","3","b"],["1","4","a"],["1","4","b"],["2","3","a"],["2","3","b"],["2","4","a"],["2","4","b"]]

你可能感兴趣的:(javaEE)