-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathGrayCode.java
More file actions
43 lines (33 loc) · 864 Bytes
/
GrayCode.java
File metadata and controls
43 lines (33 loc) · 864 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
37
38
39
40
41
42
43
package Backtracking;
import java.util.ArrayList;
/**
* Author - archit.s
* Date - 27/10/18
* Time - 10:41 PM
*/
public class GrayCode {
class IntWrapper{
int value;
public IntWrapper(int value) {
this.value = value;
}
}
public void helper(ArrayList<Integer> r, int n, IntWrapper num){
if(n == 0){
r.add(new IntWrapper(num.value).value);
return;
}
helper(r,n -1, num);
num.value = num.value ^ (1<<(n-1));
helper(r,n-1,num);
}
public ArrayList<Integer> grayCode(int a) {
ArrayList<Integer> r = new ArrayList<>();
IntWrapper wrapper = new IntWrapper(0);
helper(r,a,wrapper);
return r;
}
public static void main(String[] args) {
System.out.println(new GrayCode().grayCode(2));
}
}