C++ Solution (6ms) by using Stack and without Bit Manipulation


  • 0
    K
    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> res;
            res.push_back(0);
            if(n==0) return res;
            res.push_back(1);
            stack<int> s;
            s.push(0);
            s.push(1);
            int factor=2;
            while(n!=1){
                while(!s.empty()){
                    int temp=s.top()+factor;
                    s.pop();
                    res.push_back(temp);
                }
                for(int i=0;i<res.size();i++) s.push(res[i]);
                factor=factor*2;
                n--;
            }
            return res;
        }
    };

Log in to reply
 

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