How to generate the power-set of a given List?

后端 未结 8 1579
南方客
南方客 2020-11-29 05:58

I\'m trying to generate a collection of all 2^N - 1 possible combinations of a given List of length N. The collection will map the number of elements in a combination to an

8条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:31

    Here is a code I have tested to generate all possible combinations out of given array:

    enter code here
    import java.util.Arrays;
    
    public class PasswordGen {
    static String[] options = { "a", "b", "c", "d" };
    static String[] places = new String[options.length];
    static int count;
    
    public static void main(String[] args) {
        // Starting with initial position of a i.e. 0
        sequence(0, places.clone());
    }
    
    private static void sequence(int level, String[] holder) {
        if (level >= options.length) {
            // combination complete
            System.out.println("" + (++count) + " Combination "
                    + Arrays.toString(holder));
            return;
        }
    
        String val = options[level];
        String[] inrHolder = null;
        for (int c = 0; c < holder.length; c++) {
            inrHolder = holder.clone();
            if (inrHolder[c] == null) {
                inrHolder[c] = val;
                sequence(level + 1, inrHolder.clone());
            }
        }
        return;
    }
    }
    

提交回复
热议问题