求 {1,2,3} 幂集的算法
我觉得这有点令人困惑,因为我从未真正使用过 Java 集。有人可以尝试向我展示以下代码(最好是通过解释幂集是如何逐渐创建的)(PS 我从 stackoverflow 上的帖子中获得了此代码,所以功劳归于那个人):
public static void main(String[] args) {
Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
for (Set<Integer> s : powerSet(mySet)) {
System.out.println(s);
}
}
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<Set<T>>();
//If the input is empty, add the empty set and return
if (originalSet.isEmpty()) {
sets.add(new HashSet<T>());
return sets;
}
//Put the originalSet into an arraylist
List<T> list = new ArrayList<T>(originalSet);
//Get the first element
T head = list.get(0);
//Get everything but the first element and put into a set
Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
//For each element in the set above
for (Set<T> set : powerSet(rest)) {
//Create a new set
Set<T> newSet = new HashSet<T>();
//Add the head
newSet.add(head);
//Add the rest
newSet.addAll(set);
//Add all of newset to the result
sets.add(newSet);
//Add the current element
sets.add(set);
}
return sets;
}
I think i'm finding this a little confusing because i've never really used Java sets. Could someone please try and show me (preferably by explaining how the powerset is gradually being created) in the following code (ps i got this code from a post on stackoverflow, so credit goes to that person):
public static void main(String[] args) {
Set<Integer> mySet = new HashSet<Integer>();
mySet.add(1);
mySet.add(2);
mySet.add(3);
for (Set<Integer> s : powerSet(mySet)) {
System.out.println(s);
}
}
public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
Set<Set<T>> sets = new HashSet<Set<T>>();
//If the input is empty, add the empty set and return
if (originalSet.isEmpty()) {
sets.add(new HashSet<T>());
return sets;
}
//Put the originalSet into an arraylist
List<T> list = new ArrayList<T>(originalSet);
//Get the first element
T head = list.get(0);
//Get everything but the first element and put into a set
Set<T> rest = new HashSet<T>(list.subList(1, list.size()));
//For each element in the set above
for (Set<T> set : powerSet(rest)) {
//Create a new set
Set<T> newSet = new HashSet<T>();
//Add the head
newSet.add(head);
//Add the rest
newSet.addAll(set);
//Add all of newset to the result
sets.add(newSet);
//Add the current element
sets.add(set);
}
return sets;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑 {1, 2, 3} 的幂集。我们可以将其视为以下组合:
采用
{1} + powerset {2, 3}
行,这会扩展为:进而变为:
代码执行相同的操作,使用递归来生成较小的幂集并将每个幂集累积到列表中。
Think about the powerset of {1, 2, 3}. We can think of it as a combination of:
Taking the line
{1} + powerset {2, 3}
, this expands to:which in turn becomes:
The code is doing the same, using recursion to generate the smaller powersets and accumulating each set in a list.