Power set generated by bits

前端 未结 5 1464
青春惊慌失措
青春惊慌失措 2021-02-04 06:29

I have this code which generates power set of an array of size 4 (number is just example, less combinations to write...).

#define ARRAY_SIZE 4


unsigned int i,          


        
5条回答
  •  既然无缘
    2021-02-04 06:56

    • I started with a simple recursive permutation generator.
    • Added a length parameter and, when the length reaches 0, instead of permuting further, just print the string we have so far.
    • Added a position where we must continue picking characters from.

    The code:

    (I know some people don't like raw arrays / pointers, but it's so much easier to get great performance for this problem with that as opposed to pretty containers)

    void powerSet(char *arr, int arrLen, int pos, int startPos, int length)
    {
       if (length == 0)
          printf("%.*s\n", pos, arr);
       else
          for (int i = startPos; i < arrLen; i++)
          {
             std::swap(arr[pos], arr[i]);
             powerSet(arr, arrLen, pos+1, i+1, length - 1);
             std::swap(arr[pos], arr[i]);
          }
    }
    

    And the calling function:

    void powerSet(char *arr, int arrLen)
    {
        for (int i = 1; i <= arrLen; i++)
          powerSet(arr, 4, 0, 0, i);
    }
    

    powerSet("1234", 4) prints:

    1
    2
    3
    4
    12
    13
    14
    23
    24
    34
    123
    124
    134
    234
    1234
    

    Test.

提交回复
热议问题