Created
June 4, 2015 17:16
-
-
Save cangoal/af464a07b3538f81bc8d to your computer and use it in GitHub Desktop.
LeetCode - Gray Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| 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