Obtaining a powerset of a set in Java

后端 未结 26 2280
青春惊慌失措
青春惊慌失措 2020-11-22 11:33

The powerset of {1, 2, 3} is:

{{}, {2}, {3}, {2, 3}, {1, 2}, {1, 3}, {1, 2, 3}, {1}}

Let\'s say I have a Set in Java:<

26条回答
  •  青春惊慌失措
    2020-11-22 11:56

    This is my recursive solution which can get the power set of any set using Java Generics. Its main idea is to combine the head of the input array with all the possible solutions of the rest of the array as follows.

    import java.util.LinkedHashSet;
    import java.util.Set;
    
    public class SetUtil {
        private static  Set> combine(T head, Set> set) {
            Set> all = new LinkedHashSet<>();
    
            for (Set currentSet : set) {
                Set outputSet = new LinkedHashSet<>();
    
                outputSet.add(head);
                outputSet.addAll(currentSet);
    
                all.add(outputSet);
            }
    
            all.addAll(set);        
    
            return all;
        }
    
        //Assuming that T[] is an array with no repeated elements ...
        public static Set> powerSet(T[] input) {
            if (input.length == 0) {
                Set >emptySet = new LinkedHashSet<>();
    
                emptySet.add(new LinkedHashSet());
    
                return emptySet;
            }
    
            T head = input[0];
            T[] newInputSet = (T[]) new Object[input.length - 1];
    
            for (int i = 1; i < input.length; ++i) {
                newInputSet[i - 1] = input[i];
            }
    
            Set> all = combine(head, powerSet(newInputSet));
    
            return all;
        }
    
        public static void main(String[] args) {            
            Set> set = SetUtil.powerSet(new Integer[] {1, 2, 3, 4, 5, 6});
    
            System.out.println(set);
        }
    }
    

    This will output:

    [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5], [1, 2, 3, 4, 6], [1, 2, 3, 4], [1, 2, 3, 5, 6], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 3], [1, 2, 4, 5, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 4], [1, 2, 5, 6], [1, 2, 5], [1, 2, 6], [1, 2], [1, 3, 4, 5, 6], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 4], [1, 3, 5, 6], [1, 3, 5], [1, 3, 6], [1, 3], [1, 4, 5, 6], [1, 4, 5], [1, 4, 6], [1, 4], [1, 5, 6], [1, 5], [1, 6], [1], [2, 3, 4, 5, 6], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 4], [2, 3, 5, 6], [2, 3, 5], [2, 3, 6], [2, 3], [2, 4, 5, 6], [2, 4, 5], [2, 4, 6], [2, 4], [2, 5, 6], [2, 5], [2, 6], [2], [3, 4, 5, 6], [3, 4, 5], [3, 4, 6], [3, 4], [3, 5, 6], [3, 5], [3, 6], [3], [4, 5, 6], [4, 5], [4, 6], [4], [5, 6], [5], [6], []]
    

提交回复
热议问题