Share my C++ simple and easy to understand


  • 0
    L
    class Solution {
    public:
        vector<int> grayCode(int n) 
        {
            string temp(n,'0');
            vector<int> ret;
            unordered_set<string> dictionary;
            
            while(!dictionary.count(temp))
            {
                dictionary.insert(temp);
                ret.push_back(TwotoTen(temp));
                for(int i=n-1;i>=0;i--)
                {
                    temp[i]=temp[i]=='0'?'1':'0';
                    if(!dictionary.count(temp))
                       break;
                    else 
    				   temp[i] = temp[i] == '0' ? '1' : '0';
                }
            }
            return ret;
        }
    private:
        int TwotoTen(string str)
        { 
            int start=0,ret=0;
            while(str[start]=='0')start++;
            for(int i=str.size()-1;i>=start;i--)
            {
                if(str[i]!='0')
                ret+=pow(2,str.size()-1-i);
            }
            return ret;
        }
    };

Log in to reply
 

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