【问题标题】:What is the error in my function to generate all combinations of elements of an array?我的函数生成数组元素的所有组合有什么错误?
【发布时间】:2016-02-14 19:21:58
【问题描述】:

我正在尝试生成一个包含整数数组所有可能组合的数组的数组;不包括空集和原始集本身。这是我写的代码。外部循环一直运行,直到要包含在子集中的元素数等于原始集合中的元素数。外部 for 循环运行以添加新子集的所有元素以及一个附加元素。例如,循环应该经过:A,B 然后加 C,再加 D;生成 A,B,C 和 A,B,D。然后子集应该转移到 B,C 并添加 D 得到 B,C,D。这个过程一直持续到所有子集都被创建为止。但是我得到一个数组索引越界异常。

    double pow = Math.pow(2.0, a.length);
    char[][] b = new char[(int)pow-2][a.length-1];

    int start = 0;
    int end = 0;
    int includedElements = 1;
    int curI = 0;

    while(includedElements<=a.length) {

        if(end == a.length) {
            start = 0;
            includedElements+=1;
            end = includedElements-1;
        }

        for(int h = end+1; h<a.length; h++) {
            b[curI] = new char[includedElements];

            for(int i = start, index = 0; i<=end; i++, index++) {
                b[curI][index] = a[i];
            }

            b[curI][b[curI].length] = a[h];
        }
        curI++;

        start+=1;
        end+=1;
    }

【问题讨论】:

    标签: java arrays combinations


    【解决方案1】:

    我认为你应该首先找出你真正想要什么。组合和排列之间存在差异(请参阅here)。当你知道这一点时,你可以谷歌搜索确切的术语。我认为你想要的是没有重复的排列。这是一个可以递归解决的练习 (example)。

    【讨论】:

    • 嗯,我需要得到所有其他尺寸的子集,所以我认为我需要组合。
    猜你喜欢
    • 2019-08-06
    • 2022-12-20
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2017-08-31
    • 2021-07-30
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多