An alternative C solution based on binary form of gray codes


  • 0
    Z
    int* grayCode(int n, int* retS)
    {
      *retS = pow(2,n);
      int* ret = (int*)malloc(sizeof(int)* *retS);
      memset(ret, 0, sizeof(int)* *retS);
      int count = 0, i = 0, j=0,k=0;
      for (i = 0; i<n; i++)
      {
        count = pow(2,i); // how many 0 or 1 for the 0 1 1 0 pattern
        j = 0;
        while(j < *retS)
        {
          k = 0;
          while(k++<count)   j++;  // 0, skip
          k = 0;
          while(k++<count)   ret[j++] += pow(2,i);  // 1, so ret[j] += 2^i
          if(j>=*retS) break;
          k = 0;
          while(k++<count)   ret[j++] += pow(2,i);  // 1
          k = 0;
          while(k++<count)   j++;     //0, skip
        }
      }
      return ret;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.