Sunday, March 3, 2013
[LeetCode] Gray Code
Thought:
The generation of gray code is: Gray_code
Code:
public class Solution {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (n == 0) {
result.add(0);
return result;
}
result.addAll(grayCode(n - 1));
int x = 1 << n - 1;
for (int i = 0; i < x; i++) {
result.add(grayCode(n - 1).get(x - 1 - i) + x);
}
return result;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment