【问题标题】:finding all subsets of a given set in java and in this order在java中并按此顺序查找给定集合的所有子集
【发布时间】: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


【解决方案1】:

如果你被允许使用Guava,你可以利用它的Sets类和Sets.combinations(Set&lt;E&gt; 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);

输出:

{} , {1} , {2} , {1,2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多