Memory efficient power set algorithm

前端 未结 5 1194
鱼传尺愫
鱼传尺愫 2020-12-03 15:42

Trying to calculate all the subsets (power set) of the 9-letter string \'ABCDEFGHI\'.

Using standard recursive methods, my machine hits out of memory (1GB) error bef

5条回答
  •  没有蜡笔的小新
    2020-12-03 16:10

    I verified that this worked well:

    #include 
    
    void print_combination(char* str, char* buffer, int len, int num, int pos)
    {
      if(num == 0)
      {
        std::cout << buffer << std::endl;
        return;
      }
    
      for(int i = pos; i < len - num + 1; ++i)
      {
        buffer[num - 1] = str[i];
        print_combination(str, buffer, len, num - 1, i + 1);
      }
    }
    
    int main()
    {
      char str[] = "ABCDEFGHI";
      char buffer[10];
      for(auto i = 1u; i <= sizeof(str); ++i)
      {
        buffer[i] = '\0';
        print_combination(str, buffer, 9, i, 0);
      }
    }
    

提交回复
热议问题