java实现多个集合输出所有的排列组合

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

public class AirticketTest {
    public static void main(String[] args) {
        String[] listPrice = {"5000"};
        String[] flightMileage = {"15000"};
        String[] seatType ={"F","B","E"};
        String[] rangeType ={"D","N"};
        String[] upgradeType ={"U","N","_"};
        String[] tripType ={"O","R"};
        String[] lengthType ={"S","L","_"};
        String[] flightType ={"D","I","_"};
        String[] passengerType ={"V","N"};
        String[] VIPType ={"D","G","_"};
        String[] seasonType ={"P","N","L"};
        String[] discountType ={"N","D","J","S"};

        List> listData = new ArrayList<>();
        listData.add(Arrays.asList(listPrice));
        listData.add(Arrays.asList(flightMileage));
        listData.add(Arrays.asList(seatType));
        listData.add(Arrays.asList(rangeType));
        listData.add(Arrays.asList(upgradeType));
        listData.add(Arrays.asList(tripType));
        listData.add(Arrays.asList(lengthType));
        listData.add(Arrays.asList(flightType));
        listData.add(Arrays.asList(passengerType));
        listData.add(Arrays.asList(VIPType));
        listData.add(Arrays.asList(seasonType));
        listData.add(Arrays.asList(discountType));
        List> lisReturn = getDescartes(listData);
        //System.out.println(lisReturn);
        for( List item : lisReturn)
        {
            System.out.println(item);
        }

    }


    private static  List> getDescartes(List> list) {
        List> returnList = new ArrayList<>();
        descartesRecursive(list, 0, returnList, new ArrayList());
        return returnList;
    }

    /**
     * 递归实现
     * 原理:从原始list的0开始依次遍历到最后
     *
     * @param originalList 原始list
     * @param position     当前递归在原始list的position
     * @param returnList   返回结果
     * @param cacheList    临时保存的list
     */
    private static  void descartesRecursive(List> originalList, int position, List> returnList, List cacheList) {
        List originalItemList = originalList.get(position);
        for (int i = 0; i < originalItemList.size(); i++) {
            //最后一个复用cacheList,节省内存
            List childCacheList = (i == originalItemList.size() - 1) ? cacheList : new ArrayList<>(cacheList);
            childCacheList.add(originalItemList.get(i));
            if (position == originalList.size() - 1) {//遍历到最后退出递归
                returnList.add(childCacheList);
                continue;
            }
            descartesRecursive(originalList, position + 1, returnList, childCacheList);
        }
    }
}

效果

java实现多个集合输出所有的排列组合_第1张图片

你可能感兴趣的:(java实现多个集合输出所有的排列组合)