Topic description
Compute all subsets of n distinct integers
enter
Line 1 is an integer m, indicating that there are m sets of data to follow.
Each set of data occupies one line, and the first integer n means that there are n different integers that follow.
output
For each set of data, output different combinations of these n different integers, including empty combinations. Output “–>” before each combined output.
The requirement must be written in accordance with the recursive method taught in the class. First, output the case that contains the element, and then output the case that it does not contain, so as to ensure that the output order is consistent with the standard answer.
Sample
Input
2
2 1 2
3 1 2 3
Output
–> 1 2
–> 1
–> 2
–>
–> 1 2 3
–> 1 2
–> 1 3
–> 1
–> 2 3
–> 2
–> 3
–>
code
#include <cstring>
#include <iostream>
using namespace std;
void subset(int list[], int tag[], int n,int len) //生成子集 共2^n个
{
if (n == len)
{
cout << "-->";
for (int i = 0; i < len; i++)
{
if (tag[i] == 1)
cout <<' '<< list[i];
}
cout<<endl;
return;
}
tag[n] = 1;
subset(list, tag, n + 1,len);
tag[n] = 0;
subset(list, tag, n + 1,len);
}
int main()
{
//cout << "请您输入整数的个数:";
int m;
cin>>m;
while(m--)
{
int n;
cin >> n;
int *number = new int[n];
int *tag = new int[n];
for (int i = 0; i < n; i++)
{
cin >> number[i];
}
// for (int i = 0; i < n; i++)
// {
// cout << number[i];
// }
// cout<<endl;
//memset(tag,1,sizeof(tag[0])*n);
// for (int i = 0; i < n; i++)
// {
// cout << tag[i]<<endl;
// }
subset(number, tag, 0,n);
}
//system("pause");
return 0;
}