我正在使用递归直到array length
达到0,然后再返回到recursion
并向current
smallInteger
添加适当的元素,同时还要跟踪较小的长度使用smallIntegerLength
的整数。每次返回previous recursion call
时,我都会将smallOutputSize
加倍,因为对于许多r digits
,没有子集的是2^r
。
在output 2D ragged array
中,我存储了subsets
返回的所有recursion
。
first 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;
}
}