/*打印集合子集 位向量法和二进制法*/
import java.util.Scanner;
public class Subset {
static final int MAXN = 20;
int[] p = new int[MAXN];
int[] b = new int[MAXN];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n;
Subset s = new Subset();
while ((n = scanner.nextInt()) > 0) {
for (int i = 0; i < n; i++)
s.p[i] = scanner.nextInt();
// s.bit_subset(n, 0);
for (int i = 0; i < (1 << n); i++)
// 子集个数有1<<2个(包括空集) 编号0...1<<2-1
s.binary_subset(n, i);
}
}
// 位向量法 如果b[i]==1说明p[i]在子集中 p[i]要么在子集中要么不在
private void bit_subset(int n, int cur) {
if (cur == n) {// b[0...n-1]是0还是1已经全部确定 子集构造完毕
for (int i = 0; i < n; i++)
if (b[i] == 1)
System.out.printf("%d ", p[i]);
System.out.println();
return;
}
b[cur] = 1;// 选择p[i]
bit_subset(n, cur + 1);
b[cur] = 0; // 不选择p[i]
bit_subset(n, cur + 1);
}
// 二进制法
private void binary_subset(int n, int s) {// 对于编号为s的子集
for (int i = 0; i < n; i++)
if ((s & (1 << i)) > 0)// 按位与运算 s哪个位上有1便将其对应的数字打印出来
// 例如s=3(二进制11)那么就打印p[0]和p[1]组成的集合
System.out.printf("%d ", p[i]);
System.out.println();
}
}
打印子集
最新推荐文章于 2024-03-23 21:30:16 发布