Obtaining a powerset of a set in Java

后端 未结 26 1736
青春惊慌失措
青春惊慌失措 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:45

    Algorithm:

    Input: Set[], set_size 1. Get the size of power set powet_set_size = pow(2, set_size) 2 Loop for counter from 0 to pow_set_size (a) Loop for i = 0 to set_size (i) If ith bit in counter is set Print ith element from set for this subset (b) Print seperator for subsets i.e., newline

    #include 
    #include 
     
    void printPowerSet(char *set, int set_size)
    {
        /*set_size of power set of a set with set_size
          n is (2**n -1)*/
        unsigned int pow_set_size = pow(2, set_size);
        int counter, j;
     
        /*Run from counter 000..0 to 111..1*/
        for(counter = 0; counter < pow_set_size; counter++)
        {
          for(j = 0; j < set_size; j++)
           {
              /* Check if jth bit in the counter is set
                 If set then pront jth element from set */
              if(counter & (1<

提交回复
热议问题