The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 2: Input: 0 Output: [0] Explanation: We define the gray code sequence to begin with 0. A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1. Therefore, for n = 0 the gray code sequence is [0].
classSolution{ public List<Integer> grayCode(int n){ n = 1 << n; List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(i ^ (i >> 1)); } return list; } }
classSolution{ public List<Integer> grayCode(int n){ List<Integer> list = new ArrayList<>(); dfs(list, 1, n); return list; }
voiddfs(List<Integer> list, int cur, int n){ if (n == 0) { list.add(0); return; } if (cur > n) { return; } if (cur == 1) { list.add(0); list.add(1); } else { int len = list.size(); for (int i = 0; i < len; i++) { list.add((int) (list.get(len - i - 1) + Math.pow(2, cur - 1))); } } dfs(list, cur + 1, n); } }