There is a more effective solution than backtracking which is more intuitive:

```
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
result.add(0);
if(n == 0) return result;
for(int i = 0;i<n;++i){
int inc = 1<<i;
for(int j = result.size()-1;j>=0;--j) result.add(inc + result.get(j));
}
return result;
}
}
```