c++ code beat 100% users


  • -1
    Q

    My solution is go through the current arr in reverse order and add (1<<i) to each element, and put the result back the array.

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> ret;
            if(n == 0){
                ret.push_back(0);
                return ret;
            }
                
            ret.push_back(0);
            ret.push_back(1);
    
            for(int i = 1;i < n;i++){
                int j = ret.size()-1;
                while(j >= 0){
                    ret.push_back((1<<i)+ret[j]);
                    j--;
                }
            }
            
            return ret;
        }
    };
    

Log in to reply
 

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