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

如何从字符数组生成指定长度的组合?现有Java实现仅输出部分结果求排查

Java字符组合生成代码修复说明

问题原因

现有代码仅能输出前2组组合的核心错误有三点:

  1. 找到需要进位的索引位t01后,没有更新该位置的字符值,仅固定更新最后一位的字符,导致前两位索引不会递增,无法生成a,b开头之外的组合
  2. 后续位置赋值逻辑错误,错误读取data数组内的元素赋值,没有通过IndexChar方法获取目标位置的字符
  3. 循环结束后遗漏了最后一组合法组合

修复后核心代码

public ArrayList<char[]> generate02(int r) {
    ArrayList<char[]> combinationsList = new ArrayList<>();
    char[] data = new char[r];
    int n = CharArray01.length;
    // 初始化最小字典序组合
    for (int i = 0; i < r; i++) {
        data[i] = CharArray01[i];
    }
    while (true) {
        // 先把当前合法组合加入结果集
        combinationsList.add(data.clone());
        int t01 = r - 1;
        // 找到第一个可以递增的位置
        while (t01 >= 0 && IndexInt(data[t01]) == n - r + t01) {
            t01--;
        }
        // 所有位置都到最大值,退出循环
        if (t01 < 0) {
            break;
        }
        // 递增当前找到的位置的字符
        int currIndex = IndexInt(data[t01]);
        data[t01] = IndexChar(currIndex + 1);
        // 后续位置按顺序赋值为前一位+1的字符
        for (int i = t01 + 1; i < r; i++) {
            int prevIndex = IndexInt(data[i - 1]);
            data[i] = IndexChar(prevIndex + 1);
        }
    }
    return combinationsList;
}

验证说明

传入参数r=3,CharArray01为{'a','b','c','d','e'}时,会输出全部10组长度为3的合法组合,你给出的预期输出属于其中的子集,若需要过滤特定组合可以在加入结果集前添加对应判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:09:01