Share my 4ms C++ solution


  • 4
    M
    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> seq = {0};
            if (n == 0) {
                return seq;
            }
            
            seq = grayCode(n-1);
            int len = seq.size();
            int mask = 1 << (n-1);
            for (int i = len-1; i >= 0; i--) {
                seq.push_back(seq[i] | mask);
            }
            return seq;
        }
    };

Log in to reply
 

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