-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgray-code.java
More file actions
36 lines (29 loc) · 880 Bytes
/
Copy pathgray-code.java
File metadata and controls
36 lines (29 loc) · 880 Bytes
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
30
31
32
33
34
35
36
public class Solution {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> answer = new ArrayList<Integer>();
if (n == 0) {
answer.add(0);
return answer;
}
for (String s : search(n)) {
answer.add(Integer.parseInt(s, 2));
}
return answer;
}
public ArrayList<String> search(int n) {
if (n == 0) {
ArrayList<String> list = new ArrayList<String>();
list.add("");
return list;
}
ArrayList<String> source = search(n - 1);
ArrayList<String> generated = new ArrayList<String>();
for (String s : source) {
generated.add("0" + s);
}
for (int i = source.size() - 1; i >= 0; i--) {
generated.add("1" + source.get(i));
}
return generated;
}
}