多个数组间元素排列组合


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

/**
 * 多个数组间元素排列组合问题求解
 * 非递归计算所有组合
 * <a>https://blog.csdn.net/tyhj_sf/article/details/53893125</a>
 */
public class CalculateCombinationTest {
    public static void calculateCombination(List<List<String>> inputList) {
        List<Integer> combination = new ArrayList<Integer>();
        int n=inputList.size();
        for (int i = 0; i < n; i++) {
            combination.add(0);
        }
        int i=0;
        boolean isContinue=false;
        do{
            //打印一次循环生成的组合
            for (int j = 0; j < n; j++) {
                System.out.print(inputList.get(j).get(combination.get(j))+", ");
            }
            System.out.println();

            i++;
            combination.set(n-1, i);
            for (int j = n-1; j >= 0; j--) {
                if (combination.get(j)>=inputList.get(j).size()) {
                    combination.set(j, 0);
                    i=0;
                    if (j-1>=0) {
                        combination.set(j-1, combination.get(j-1)+1);
                    }
                }
            }
            isContinue=false;
            for (Integer integer : combination) {
                if (integer != 0) {
                    isContinue=true;
                }
            }
        }while (isContinue);
    }

    public static void main(String[] args) {
        List<String> list1 = new ArrayList<>();
        list1.add("0");
        list1.add("1");
        list1.add("2");
        List<String> list2 = new ArrayList<>();
        list2.add("a");
        list2.add("b");
        list2.add("c");
        List<String> list3 = new ArrayList<>();
        list3.add("@");
        list3.add("#");
        list3.add("$");
        List<List<String>> allList = new ArrayList<>();
        allList.add(list1);
        allList.add(list2);
        allList.add(list3);
        calculateCombination(allList);
    }
}

posted @ 2020-11-27 14:03  fly_bk  阅读(570)  评论(0编辑  收藏  举报