你想要的就是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}
is3
combined with{{}} = { {}, {3} }
;
- Remove
- 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} }.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)