Hi guys,
the improved solution to gray code generation says
… Gray code property being violated from 010 to 100. However, it is preserved everywhere else.
The property also doesn’t hold for wrap around: from 110 to 000.
I also have some suggestion about the code. The condition
if (numBits == 1) {
return Arrays.asList(0, 1);
}
is unnecessary, since you can build from the solution of 0 bits.
You also create a new ArrayList on each iteration. Since we don’t need to keep the solution to (n-1) problem, we can just modify that solution and return it.
Note that you have to replace Arrays.asList(0)
to new ArrayList<>(Arrays.asList(0))
to allow adding new elements to it. Something like this:
public static List<Integer> generateGrayCode(int n) {
if (n == 0) {
return new ArrayList<>(Arrays.asList(0));
}
List<Integer> previous = generateGrayCode(n - 1);
for (int i = previous.size() - 1; i >= 0; i--) {
previous.add(previous.get(i) | (1 << (n - 1)));
}
return previous;
}