```
var grayCode = function(n) {
if(n == 0){
return [0];
}
let grayHash = {};
let indexHash = {};
let initarr = Array.from(new Array(n), (e) => e = 0);
let step = 0;
util(initarr, 0);
function util(arr){
if(arr.length == n && grayHash[arr]){
return;
}
if(arr.length == n){
step++;
grayHash[arr] = step;
indexHash[step] = [...arr];
}
for(let k = 0; k < n; k++){
arr[k] = arr[k] ^ 1;
util(arr);
arr[k] = arr[k] ^ 1; // backtrack
}
return true;
}
let i = 1;
let grayCode = [];
for(let key in indexHash){
var digit = parseInt(indexHash[i].join(""), 2);
grayCode.push(digit);
i++;
}
return grayCode;
};
```