Closed. This question is off-topic. It is not currently accepting answers. Learn more
想改进这个问题吗?Update the question所以堆栈溢出的值小于aa>。
我正在尝试递归地找到一个集合的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);
    }

最佳答案

尝试递归思考:
基本情况)空集的powerset是空集
rec.case)这样一个列表的powerset[firstElemnt]+restOfTheListrestOfTheList的powerset加上与restOfTheList链接的firstElemnt的powerset的每个元素
例子:
给出一个列表[a,b,c]:
[]->[[]]的电源集(设置为空集)
[a]>[[],[a]]的powerset(添加到前一个powerset的每个元素中)
[a,b]>[[],[a],[b],[a,b]]的电源集(在以前的电源集的每个元素中添加了a
[a,b,c]>[[],[a],[b],[a,b],[c],[a,c],[a,b,c]]的电源组(将b添加到以前的电源组的每个元素)
算法

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;
}

测试
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;

关于java - 递归查找集合中最强大的一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20551862/

10-12 14:24