- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgrayCode.java
More file actions
Latest commit
30 lines (26 loc) · 728 Bytes
/
Copy pathgrayCode.java
File metadata and controls
30 lines (26 loc) · 728 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
//一道模拟题,以3位格雷码为例。
//0 0 0
//0 0 1
//0 1 1
//0 1 0
//1 1 0
//1 1 1
//1 0 1
//1 0 0
//可以看到第n位的格雷码,等于n-1位格雷码 加上 1<<(n-1)和n-1位格雷码的逆序。
publicclassSolution {
publicArrayList<Integer> grayCode(intn) {
if(n==0) {
ArrayList<Integer> result = newArrayList<Integer>();
result.add(0);
returnresult;
}
ArrayList<Integer> tmp = grayCode(n-1);
intaddNumber = 1 << (n-1);
ArrayList<Integer> result = newArrayList<Integer>(tmp);
for(inti=tmp.size()-1;i>=0;i--) {
result.add(addNumber + tmp.get(i));
}
returnresult;
}
}