Skip to content

Instantly share code, notes, and snippets.

@cangoal
Created June 4, 2015 17:16
Show Gist options
  • Save cangoal/af464a07b3538f81bc8d to your computer and use it in GitHub Desktop.
Save cangoal/af464a07b3538f81bc8d to your computer and use it in GitHub Desktop.
LeetCode - Gray Code
//
public List<Integer> grayCode(int n) {
ArrayList<Integer> ret = new ArrayList<Integer>();
if(n < 0) return ret;
ret.add(0);
if(n == 0) return ret;
for(int i=0; i<n; i++){
ArrayList<Integer> temp = new ArrayList<>();
for(int j=ret.size()-1; j>=0; j--){
temp.add((1<<i) + ret.get(j)); // the priority of +/- operation is higher then >>/<< shift operation
}
ret.addAll(temp);
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment