下面是用c++实现的输出n个整数的全排列
# include <iostream>
#include <windows.h>
using namespace std;
void swap(int &a, int &b)
{
//交换a和b
int temp = a;
a = b;
b = temp;
}
void perm(int list[], int k, int m)
{
if (k == m)//递归的基础部分
{
for (int i = 0; i <= m; i++)
{
cout << list[i];
}
cout << endl;
}
else
{
for (int i = k; i <= m; i++)
{
swap(list[k], list[i]);
perm(list, k + 1, m);
swap(list[k], list[i]);
}
}
}
int main()
{
int list[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
cout << "Please enter a number n in order to generate the full array from 1 to n (Not exceeding 9)." << endl;
int n;
cin >> n;
while (n > 9 || n <1)
{
cout << "Out of range, please enter again." << endl;
cin >> n;
}
perm(list, 0, n - 1);
system("pause");
return 0;
}
下面是c++实现n个整数的所有子集
#include <string.h>
#include <iostream>
#include <windows.h>
using namespace std;
int getArrayLen(int array[])
{
return (sizeof(array) / sizeof(array[0]));
}
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] = 0;
subset(list, tag, n + 1,len);
tag[n] = 1;
subset(list, tag, n + 1,len);
}
int main(int argc, char* argv[])
{
cout << "请您输入整数的个数";
int n;
cin >> n;
int *b = new int[n];
int *c = new int[n];
for (int i = 0; i < n; i++)
{
cin >> b[i];
}
for (int i = 0; i < n; i++)
{
cout << b[i];
}
//int a[] = { 1,2,3,4 };
//int tag[4];
subset(b, c, 0,n);
system("pause");
return 0;
}