12 lines 4ms C++ Solution based on bitwise operation


  • 0
    K

    vector<int> grayCode(int n) {
    if (n == 0) return vector<int>(1, 0);
    vector<int> res(1 << n, 0);
    res[1] = 1;
    int t = 2;
    for (int i = 2; i <= n; ++i){
    for (int j = 0; j < t; ++j)
    res[t + j] = *(res.rend() - t + j) | t;
    t = t << 1;
    }
    return res;
    }


  • 0
    K

    more concise code:

    vector<int> grayCode(int n) {
    vector<int> res(1<<n, 0);
    for (int i = 0; i <= 1<<n; ++i) res[i] = i^(i>>1);
    return res;
    }


Log in to reply
 

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