知识点:格雷编码的生成过程, G(i) = i ^ (i/2);
如 n = 3:
G(0) = 000,
G(1) = 1 ^ 0 = 001 ^ 000 = 001
G(2) = 2 ^ 1 = 010 ^ 001 = 011
G(3) = 3 ^ 1 = 011 ^ 001 = 010
G(4) = 4 ^ 2 = 100 ^ 010 = 110
G(5) = 5 ^ 2 = 101 ^ 010 = 111
G(6) = 6 ^ 3 = 110 ^ 011 = 101
G(7) = 7 ^ 3 = 111 ^ 011 = 100
class Solution { List<Integer> res = new ArrayList<>(); public List<Integer> grayCode(int n) { for(int i = 0; i < 1 << n; i++) { res.add(i ^ (i / 2)); } return res; } }
方法二:dfs
class Solution { List<Integer> res = new ArrayList<>(); public List<Integer> grayCode(int n) { int total = 1 << n; boolean[] st = new boolean[total]; st[0] = true; dfs(0,n,st); return res; } public void dfs(int cur, int n, boolean[] st) { if(cur < 1 << n) res.add(cur); for(int i = 0; i < n; i++) { int next = cur ^ (1 << i); if(st[next]) continue; st[next] = true; dfs(next,n,st); } } }