C++ 4ms iterative solution


  • 0
    class Solution {
    public:
    vector<int> grayCode(int n) {
        vector <int> res;
        if (n<0) return res;
        res.push_back(0);
        int k=0,sz=1;
        while(k<n){
            for (int i=sz-1;i>=0;i--){
                res.push_back(res[i]);
                res.back()+=sz;
            }
            sz*=2; k++;
        }
        return res;
    }
    };

Log in to reply
 

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