[英]finding all subsets of a given set in java and in this order
實際上我想以這種方式編寫給定集合的所有子集:
例如,如果我的集合是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,},
我的問題是,
。 我不想在每個子集,
末尾和整個 output 的末尾都有。 你能幫我解決這個問題,得到一個像{}, {1}, {2}, {1,2}
這樣的 output 嗎? 最后我想對它們進行排序
如果你被允許使用Guava ,你可以利用它的Sets
class 和Sets.combinations(Set<E> set, int size)
方法:
static void printSubsets(Set<Integer> a) {
String combinations = IntStream.rangeClosed(0, a.size()).boxed()
.flatMap(i -> Sets.combinations(a, i).stream()
.sorted(Comparator.comparingInt(Collections::max)))
.map(subSet -> subSet.stream().sorted().map(String::valueOf)
.collect(Collectors.joining(",", "{", "}")))
.collect(Collectors.joining(" , "));
System.out.println(combinations);
}
然后:
Set<Integer> set = Set.of(1, 2);
printSubsets(set);
Output:
{} , {1} , {2} , {1,2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.