我试图以递归的方式找到一个集合的powerset然后打印出我非常感谢任何帮助的结果将非常感激。
public static ArrayList<String> getpowerset(int a[],int n, ArrayList<String> power){
if(n<0)
{
return null;
}
if(n==0)
{
if(power==null)
power=new ArrayList<String>();
power.add(" ");
return power;
}
power=getpowerset(a, n-1, power);
ArrayList<String> tmp=new ArrayList<String>();
for(String s:power)
{
if(s.equals(" "))
tmp.add(""+a[n-1]);
else
tmp.add(s+a[n-1]);
}
power.addAll(tmp);
return power;
for (int i = 0; i<power.size();i++){
System.out.println(power);
}
答案 0 :(得分:1)
尝试递归思考:
firstElemnt
] + restOfTheList
这样的列表的powerset是restOfTheList
的powerset加上restOfTheList
与firstElemnt
链接的powerset的每个元素/ LI>
示例:强>
给出一个列表[a,b,c]:
a
添加到之前powerset的每个元素中)b
添加到之前powerset的每个元素中)c
对于以前的powerset的每个元素)<强>算法强>
public static List<List<String>> powerset(final LinkedList<String> originalSet) {
final List<List<String>> powerset = new LinkedList<List<String>>();
//Base case: empty set
if ((originalSet == null) || (originalSet.size() == 0)) {
final List<String> set = new ArrayList<String>();
//System.out.println(set);
powerset.add(set);
} else {
//Recursive case:
final String firstElement = originalSet.removeFirst();
final List<List<String>> prevPowerset = powerset(originalSet);
powerset.addAll(prevPowerset);
//Add firstElement to each of the set of the previuos powerset
for (final List<String> prevSet : prevPowerset) {
final List<String> newSet = new ArrayList<String>(prevSet);
newSet.add(firstElement);
//System.out.println(newSet);
powerset.add(newSet);
}
}
return powerset;
}
<强> TEST 强>
public static void main(final String[] args) {
final LinkedList<String> originalSet = new LinkedList<String>();
originalSet.add("a");
originalSet.add("b");
originalSet.add("c");
System.out.println("The powerset of " + originalSet + " is:");
System.out.println(powerset(originalSet));
}
<强>输出强>
The powerset of [a, b, c] is:
[[], [c], [b], [c, b], [a], [c, a], [b, a], [c, b, a]]
请注意,我已导入以下类:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;