Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all subsets of a set (PowerSet) [duplicate]

Tags:

java

set

I want to find all subsets of a given set. I got string set defined as following: HashSet<String> L and I want to use in a loop all of its subsets as: for each A subset of L do something. Is there an easy way with low complexity to do that?

like image 223
SharonKo Avatar asked Dec 06 '22 05:12

SharonKo


1 Answers

OK, I used this algorithm (L is a set of strings):

powerSet = new HashSet<List<String>>();
List<String> mainList = new ArrayList<String>(L);
buildPowerSet(mainList,mainList.size());

And,

private static void buildPowerSet(List<String> list, int count)
{
    powerSet.add(list);

    for(int i=0; i<list.size(); i++)
    {
        List<String> temp = new ArrayList<String>(list);
        temp.remove(i);
        buildPowerSet(temp, temp.size());
    }
}
like image 199
SharonKo Avatar answered Dec 18 '22 02:12

SharonKo