Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added GrayCode.java #33

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Programming_Languages/Java/GrayCode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.*;

public class GrayCode {

public static List grayCode(int n) {
List< Integer> ans = new ArrayList< >();
if (n == 0) {
ans.add(0);
return ans;
}
backtrack(ans, n);
return ans;
}

static int temp;

private static void backtrack(List ans, int n) {
if (n == 0) {
ans.add(temp);
return;
}

backtrack(ans, n - 1);

temp = temp ^ (1 << (n - 1));
backtrack(ans, n - 1);
}

public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
List ans = grayCode(scn.nextInt());
Collections.sort(ans);
System.out.println(ans);
}
}