-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy path89.java
48 lines (42 loc) · 1.33 KB
/
89.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> grayCode(int n) {
helper(0, n, false);
return result;
}
private void helper(int base, int count, boolean swap) {
if (count == 0) {
result.add(base);
return;
}
if (!swap) {
helper(base+0, count-1, false);
helper(base+(1<<(count-1)), count-1, true);
} else {
helper(base+(1<<(count-1)), count-1, false);
helper(base+0, count-1, true);
}
}
}
__________________________________________________________________________________________________
sample 35376 kb submission
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
result.add(0);
dfs(0, n, result);
return result;
}
private void dfs(int i, int n, List<Integer> result) {
if (i == n) return;
else {
int flipper = 1 << i;
for (int j = result.size() - 1; j >= 0; j--)
result.add(result.get(j) | flipper);
dfs(i + 1, n, result);
}
}
}
__________________________________________________________________________________________________