My recursive cpp code


  • 0
    C
    class Solution {
    public:
        vector<int> grayCode(int n) 
        {
           if(n == 0) return vector<int>{0};
           if(n == 1) return vector<int>{0, 1};
           
           vector<int> res;
           vector<int> subres = grayCode(n-1);
           for(int i=0; i < subres.size(); i++)
           {
               subres[i] <<= 1;
               if(i%2 == 0) 
               {
                   res.push_back(subres[i]);
                   res.push_back(subres[i] + 1);
               }
               else
               {
                   res.push_back(subres[i] + 1);
                   res.push_back(subres[i]);
               }
           }
           
           return res;
        }
    };

Log in to reply
 

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