forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGrayCode.java
29 lines (28 loc) · 868 Bytes
/
GrayCode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
public ArrayList<Integer> grayCode(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> result = new ArrayList<Integer>();
if (n <= 1) {
for (int i = 0; i <= n; i++){
result.add(i);
}
return result;
}
result = grayCode(n - 1);
ArrayList<Integer> r1 = reverse(result);
int x = 1 << (n-1);
for (int i = 0; i < r1.size(); i++) {
r1.set(i, r1.get(i) + x);
}
result.addAll(r1);
return result;
}
public ArrayList<Integer> reverse (ArrayList<Integer> r) {
ArrayList<Integer> rev = new ArrayList<Integer>();
for (int i = r.size() - 1; i >= 0; i--) {
rev.add(r.get(i));
}
return rev;
}
}