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

Java combinationUtil函数无法返回组合值,仅能打印正确值求助

问题排查与修复:组合生成函数无法返回组合列表

你的问题核心出在这几个点:

  1. 返回类型不匹配:函数定义为返回int,只能输出单个整数,完全无法承载多个组合构成的列表。
  2. 递归结果未收集:递归调用combinationUtil时,你没有保存它生成的数值,这些有效组合直接丢失,最终函数只会返回末尾的默认值0。
  3. 逻辑设计偏差:当前逻辑仅在生成单个组合时返回该数值,没有设计累积所有组合的机制。

修复方案

改用传入集合参数的方式来收集所有组合,而非让函数返回单个值。以下是修改后的代码:

import java.util.List;

static void combinationUtil(int arr[], int data[], int start,
                            int end, int index, int r, List<Integer> result) {
    if (index == r) {
        String num = "";
        for (int i = 0; i < r; i++) {
            num += Integer.toString(data[i]);
        }
        result.add(Integer.parseInt(num)); // 将生成的组合存入结果列表
        return;
    }

    for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
        data[index] = arr[i];
        combinationUtil(arr, data, i + 1, end, index + 1, r, result); // 递归时传递结果列表
    }
}

使用示例

调用时需先创建一个列表来接收结果:

List<Integer> combinations = new ArrayList<>();
int[] arr = {1,2,3,4};
int r = 2; // 指定生成2个数的组合
combinationUtil(arr, new int[r], 0, arr.length-1, 0, r, combinations);
// 此时combinations中已保存所有生成的组合整数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:22:42