89 Gray Code
89. Gray Code
1. Question
00 - 0
01 - 1
11 - 3
10 - 22. Implementation
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
int[] num = new int[1];
getGrayCode(n, num, res);
return res;
}
public void getGrayCode(int n, int[] num, List<Integer> res) {
if (n == 0) {
res.add(num[0]);
return;
}
// For each bit of the num, we either leave it alone or invert the current bit
// Leave the current bit alone
getGrayCode(n - 1, num, res);
// Invert the current bit
num[0] ^= (1 << (n -1));
getGrayCode(n - 1, num, res);
}
}3. Time & Space Complexity
Last updated