Java 计算一组数的所有子集

Java 计算一组数的所有子集,第1张

Java 计算一组数的所有子集

你想要的就是Powerset。这是一个简单的实现:

public static Set<Set<Integer>> powerSet(Set<Integer> originalSet) {        Set<Set<Integer>> sets = new HashSet<Set<Integer>>();        if (originalSet.isEmpty()) { sets.add(new HashSet<Integer>()); return sets;        }        List<Integer> list = new ArrayList<Integer>(originalSet);        Integer head = list.get(0);        Set<Integer> rest = new HashSet<Integer>(list.subList(1, list.size()));        for (Set<Integer> set : powerSet(rest)) { Set<Integer> newSet = new HashSet<Integer>(); newSet.add(head); newSet.addAll(set); sets.add(newSet); sets.add(set);        }        return sets;    }

我将为你提供一个示例,说明该算法如何用于的幂集{1, 2, 3}:

  • Remove
    {1}
    , and execute powerset for
    {2, 3}
    ;
  • Remove
    {2}
    , and execute powerset for
    {3}
    ;
    • Remove
      {3}
      , and execute powerset for
      {}
      ;
    • Powerset of
      {}
      is
      {{}}
      ;
    • Powerset of
      {3}
      is
      3
      combined with
      {{}} = { {}, {3} }
      ;
  • Powerset of
    {2, 3} is {2}
    combined with
    { {}, {3} } = { {}, {3}, {2}, {2, 3} }
    ;
  • Powerset of
    {1, 2, 3} is {1}
    combined with
    { {}, {3}, {2}, {2, 3} } = { {}, {3}, {2}, {2, 3}, {1}, {3, 1}, {2, 1}, {2, 3, 1} }.


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5427431.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存