1 public class Solution { 2 public ArrayList<Integer> grayCode(int n) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 ArrayList<Integer> result = new ArrayList<Integer>(); 6 if(n < 0) 7 return result; 8 int count = 1 << n; 9 for(int i = 0; i < count; i++) 10 result.add(i^(i>>1)); 11 return result; 12 13 } 14 }
1 public class Solution { 2 public ArrayList<Integer> grayCode(int n) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 ArrayList<Integer> result = new ArrayList<Integer>(); 6 if(n <= 1){ 7 result.add(0); 8 if(n == 1){ 9 result.add(1); 10 } 11 return result; 12 } 13 14 ArrayList<Integer> pre = grayCode(n - 1); 15 int highest = 1 << (n - 1); 16 result.addAll(pre); 17 for(int i = pre.size() - 1; i >= 0 ; i --){ 18 result.add(pre.get(i) + highest); 19 } 20 return result; 21 } 22 }