【发布时间】:2023-03-19 23:50:01
【问题描述】:
实际上我想以这种方式编写给定集合的所有子集:
例如,如果我的集合是A:{1,2},我想拥有{} , {1} , {2} , {1,2}
这是我尝试过的:
static void printSubsets(java.util.Set<Integer> a) {
int n = a.size();
// Run a loop for printing all 2^n
// subset one by one
for (int i = 0; i < (1 << n); i++) {
System.out.print("{");
// Print current subset
for (int j = 0; j < n; j++) {
// (1<<j) is a number with jth bit 1
// so when we 'and' them with the
// subset number we get which numbers
// are present in the subset and which
// are not
if ((i & (1 << j)) > 0)
System.out.print(a.toArray()[j] + ",");
if (j == n - 1)
System.out.print(a.toArray()[j]);
}
System.out.print("} , ");
}
}
这是输出{} , {1,} , {2,} , {1,2,} ,
我的问题是 , 。我不想在每个子集的末尾和整个输出的末尾都有,。
你能帮我解决这个问题,得到像{} , {1} , {2} , {1,2} 这样的输出吗?最后我想对它们进行排序
【问题讨论】:
-
嘿!我得到不同的输出。而且输出是错误的。最好不要像构建字符串那样对其进行编码,而是像实际创建子集并将它们收集起来以作为最后一步进行打印。
-
你可以使用
StringJoiner,例如stackoverflow.com/a/27522724/1225328。
标签: java for-loop if-statement set subset