Search for all subsets of a set (PowerSet)

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

+4
source share
2 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()); } } 
+12
source

So you want to find all the nonempty subsets of Set that will be {a} {b} {ab} for the set {ab}? This may not be the quickest solution, but you can go through all the elements in your set one by one, start from the first and define all nonempty sets β†’ the first element, go to the second element and copy all the sets saved so far and add to all copied a new item plus and a new set with only a new item. Now you have all the subsets of the previous elements plus the set of all these sets with the element added added plus one with the new element. This can then be repeated for all elements and should yield all nonempty subsets.

 Set<String> inputSet = new HashSet<String>(); inputSet.add("a"); inputSet.add("b"); inputSet.add("c"); inputSet.add("d"); List<Set<String>> subSets = new ArrayList<Set<String>>(); for(String addToSets:inputSet) { List<Set<String>> newSets = new ArrayList<Set<String>>(); for(Set<String> curSet:subSets) { Set<String> copyPlusNew = new HashSet<String>(); copyPlusNew.addAll(curSet); copyPlusNew.add(addToSets); newSets.add(copyPlusNew); } Set<String> newValSet = new HashSet<String>(); newValSet.add(addToSets); newSets.add(newValSet); subSets.addAll(newSets); } for(Set<String> set:subSets) { for(String setEntry:set) { System.out.print(setEntry + " "); } System.out.println(); } 

What will be output:

 ddbbdcdbcbccdadbabadc adbcabcacaa 
+3
source

Source: https://habr.com/ru/post/1502170/


All Articles