为什么返回整数数组的所有子集时出现无限循环?

时间:2019-12-20 10:47:34

标签: c++ arrays recursion data-structures subset

我正在使用递归直到array length达到0,然后再返回到recursion并向current smallInteger添加适当的元素,同时还要跟踪较小的长度使用smallIntegerLength的整数。每次返回previous recursion call时,我都会将smallOutputSize加倍,因为对于许多r digits,没有子集的是2^r

output 2D ragged array中,我存储了subsets返回的所有recursionfirst column of the ragged array in every row存储corresponding subset length

  

示例输入:

     

3

     

15 20 12

     

示例输出:

     

[](这仅表示一个空数组,不必担心正方形   括号)

     

12

     

20

     

20 12

     

15

     

15 12

     

15 20

     

15 20 12

#include <iostream>
using namespace std;

int subset(int input[], int n, int output[][20])
{
    if (n == 0)
    {
        output[0][0] = 0;
        output[0][1] = ' ';
        output[1][0] = '\0';
        return 1;
    }

    else
    {
        int smallIntegerLength = n - 1;
        int *smallInteger = new int[smallIntegerLength];
        for (int i = 0; input[i] != '\0'; i++)
            smallInteger[i] = input[i];
        smallInteger[smallIntegerLength - 1] = '\0';

        int smallOutputSize = subset(smallInteger, smallIntegerLength, output);

        int i, j, tempCounter;
        for (i = 0; i < smallOutputSize; i++)
        {
            tempCounter = 0;
            for (j = 1; smallInteger[j] != '\0'; j++)
            {
                tempCounter++;
                output[i][j] = smallInteger[j];
            }
            output[i][j] = '\0';
            output[i][0] = tempCounter;
        }

        return 2 * smallOutputSize;
    }
}

int main()
{
    int input[20], length, output[35000][20];
    cin >> length;
    for (int i = 0; i < length; i++)
        cin >> input[i];

    int size = subset(input, length, output);

    for (int i = 0; i < size; i++)
    {
        for (int j = 1; j <= output[i][0]; j++)
        {
            cout << output[i][j] << " ";
        }
        cout << endl;
    }
}

0 个答案:

没有答案