We can find the regular pattern in gray code, which is:
the first of the combinations of n-digit gray code is exactly the combinations of (n-1)-digit gray code, the second half is consist of 1<<(n-1) + each elements from the end to the start in (n-1)-digit gray code.
code:
public class Solution { public List<Integer> grayCode(int n) { List<Integer> list = new ArrayList<>(); if(n == 0){ list.add(0); return list; } if(n == 1){ list.add(0); list.add(1); return list; } int i = 1 << (n-1); list = grayCode(n-1); for(int j = list.size() - 1; j >=0; j--) list.add(i+list.get(j)); return list; } }