You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何实现ArrayList<char[]>的笛卡尔积,得到所有字符组合?

你之前写的是全排列算法,和你要实现的笛卡尔积逻辑完全不匹配,不需要在原有代码上修改,直接按以下思路实现即可。

实现思路

  • 初始结果集先放一个空的字符列表,用来逐步拼接元素
  • 遍历输入的每一个字符子数组:
    • 新建临时结果集
    • 把当前结果集里的每一个已有组合,分别拼接当前字符子数组的每一个字符,存入临时结果集
    • 把临时结果集赋值给当前结果集,继续处理下一个子数组
  • 所有子数组处理完成后,结果集就是你要的笛卡尔积

完整可运行代码

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

public class CartesianProduct {
    public static void main(String[] args) {
        // 构造你给出的测试输入
        ArrayList<char[]> preCombination = new ArrayList<>();
        preCombination.add(new char[]{'a'});
        preCombination.add(new char[]{'b', 'B'});
        preCombination.add(new char[]{'c', 'C'});

        ArrayList<char[]> result = getCartesianProduct(preCombination);
        
        // 测试输出
        for (char[] arr : result) {
            System.out.print("[");
            for (int i = 0; i < arr.length; i++) {
                if (i > 0) System.out.print(",");
                System.out.print("'" + arr[i] + "'");
            }
            System.out.println("]");
        }
    }

    public static ArrayList<char[]> getCartesianProduct(ArrayList<char[]> input) {
        ArrayList<List<Character>> tempResult = new ArrayList<>();
        // 初始化临时结果,先放一个空列表用来拼接
        tempResult.add(new ArrayList<>());

        for (char[] currentArray : input) {
            ArrayList<List<Character>> newTemp = new ArrayList<>();
            // 遍历已有的每一个组合
            for (List<Character> existingComb : tempResult) {
                // 遍历当前子数组的每一个字符,拼接到已有组合后面
                for (char c : currentArray) {
                    List<Character> newComb = new ArrayList<>(existingComb);
                    newComb.add(c);
                    newTemp.add(newComb);
                }
            }
            // 更新临时结果为新拼接好的集合
            tempResult = newTemp;
        }

        // 把List<Character>转换成你要的char[]类型,封装到结果集合
        ArrayList<char[]> finalResult = new ArrayList<>();
        for (List<Character> comb : tempResult) {
            char[] charArr = new char[comb.size()];
            for (int i = 0; i < comb.size(); i++) {
                charArr[i] = comb.get(i);
            }
            finalResult.add(charArr);
        }
        return finalResult;
    }
}

输出结果

运行上述代码会得到你期望的输出:

['a','b','c']
['a','b','C']
['a','B','c']
['a','B','C']

内容的提问来源于stack exchange,提问作者Eugene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:09:03