我想在开头说这是为了学校的作业,所以虽然我需要帮助,但最好是指出正确的方向,而不是给我代码来使用。
因此,赋值能够打印出任何给定集的PowerSet (给定集合的所有子集的集合)。我在Java方面经验丰富,但递归是我的弱点之一,所以我很难想象这一点。
我的方法返回所有子集,其中包括'd‘和空集。
到目前为止,我的情况如下:
public static TreeSet<TreeSet<Character>> powerSet(TreeSet<Character> setIn)
{
Comparator<TreeSet<Character>> comp = new Comparator<TreeSet<Character>>()
{
@Override
public int compare(TreeSet<Character> a, TreeSet<Character> b)
{
return a.size() - b.size();
}
};
TreeSet<TreeSet<Character>> temp = new TreeSet<TreeSet<Character>>(comp);
if (setIn.isEmpty())
{
temp.add(new TreeSet<Character>());
return temp;
}
Character first = setIn.first();
msg(first);
setIn.remove(first);
TreeSet<TreeSet<Character>> setA = powerSet(setIn);
temp.addAll(setA);
for (TreeSet<Character> prox : setA)
{
TreeSet<Character> setB = new TreeSet<Character>(prox);
setB.add(first);
temp.add(setB);
}
return temp;
}给定集合
[a, b, c, d]这个方法给了我一套
[[], [d], [c, d], [b, c, d], [a, b, c, d]]但我们知道PowerSet应该是
[[], [a], [b], [c], [d], [a, b], [a, c], [a, d], [b, c], [b, d], [c, d],
[a, b, c], [a, b, d], [a, c, d], [b, c, d], [a, b, c, d]]任何向正确方向发展的帮助都将不胜感激。
编辑:我的问题是一个非常愚蠢的问题。我忘记适当地设置比较器,这就排除了结果。我将比较器修正为正确排序,而不丢弃集合。
下面是:
public int compare(TreeSet<Character> a, TreeSet<Character> b)
{
if(a.equals(b))
return 0;
if(a.size() > b.size())
return 1;
return -1;
}发布于 2013-11-11 23:04:45
广泛编辑:
解决方案比我最初想象的要简单得多。除了以下内容之外,您做的一切都很好:在从集合中移除第一个元素之前,将该集合添加到temp集中。
就像这样:
temp.add(setIn);
Character first = setIn.first();
msg(first);
setIn.remove(first);发布于 2013-11-11 23:02:23
到目前为止看起来还不错。
您正在构建包含第一个元素的每个可能的子集,可以非常简单地对初始集合的每个元素进行扩展。只需要做你已经在做的事情,但是对于初始集的一个不同的元素。
这应该能让你更接近powerset。
https://stackoverflow.com/questions/19917621
复制相似问题