1、输出 N 个整数的全排列。输入 N 个不同的元素,通过递归的方法输出 N
个元素。
2、输出 N 个整数的所有子集。
详细解答如下,望采纳
#include <stdio.h>
#include <stdbool.h>
#define N 5
int a[N] = {1, 2, 3, 4, 5};
bool used[N] = {0};
void permute(int depth) {
if (depth == N) {
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
printf("\n");
return;
}
for (int i = 0; i < N; i++) {
if (!used[i]) {
used[i] = true;
a[depth] = i;
permute(depth+1);
used[i] = false;
}
}
}
int main() {
permute(0);
return 0;
}
#include <stdio.h>
#include <stdbool.h>
#define N 5
int a[N] = {1, 2, 3, 4, 5};
bool used[N] = {0};
void subset(int depth, bool has_element) {
if (depth == N) {
if (has_element) {
printf("{ ");
for (int i = 0; i < N; i++) {
if (used[i]) {
printf("%d ", a[i]);
}
}
printf("}\n");
} else {
printf("{}\n");
}
return;
}
used[depth] = false;
subset(depth+1, has_element);
used[depth] = true;
subset(depth+1, true);
}
int main() {
subset(0, false);
return 0;
}