JavaScript recursive solution using reflected Gray code


  • 0
    var grayCode = function(n) {
        if (n === 0) return [0];
        const res = grayCode(n - 1);
        const mask = 1 << n - 1;
        for (let i = res.length - 1; i >= 0; i--) {
            res.push(res[i] | mask);
        }
        return res;
    };
    

    The strategy is described here and can also be done iteratively.


Log in to reply
 

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