My simple 4ms C++ solution


  • 0
    J
    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> code;
            if (n == 0)
            {
                code.push_back(0);
            }
            else
            {
                vector<int> c;
                int m;
                m = 1 << (n-1);
                c = grayCode(n-1);
                code.reserve(2*m);
                for (int i = 0; i < m; i++)
                    code.push_back(c[i]);
                for (int i = m-1; i >= 0; i--)
                    code.push_back(c[i]|m);
            }
            return code;
        }
    };

Log in to reply
 

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