Given a number n, the task is to generate n bit Gray codes (generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit)
Input : 2 Output : 0 1 3 2 Explanation : 00 - 0 01 - 1 11 - 3 10 - 2 Input : 3 Output : 0 1 3 2 6 7 5 4
We have discussed an approach in Generate n-bit Gray Codes
This article provides a backtracking approach to the same problem. Idea is that for each bit out of n bit we have a choice either we can ignore it or we can invert the bit so this means our gray sequence goes upto 2 ^ n for n bits. So we make two recursive calls for either inverting the bit or leaving the bit as it is.
0 1 3 2 6 7 5 4
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Generate n-bit Gray Codes | Set 2
- Generate n-bit Gray Codes
- Gray to Binary and Binary to Gray conversion
- Generate all distinct subsequences of array using backtracking
- Code Converters - Binary to/from Gray Code
- Binary to Gray code using recursion
- Decimal Equivalent of Gray Code and its Inverse
- Inserting m into n such that m starts at bit j and ends at bit i.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- The Knight's tour problem | Backtracking-1
- Rat in a Maze | Backtracking-2
- N Queen Problem | Backtracking-3
- Subset Sum | Backtracking-4
- Hamiltonian Cycle | Backtracking-6
- Solving Cryptarithmetic Puzzles | Backtracking-8
- Word Break Problem using Backtracking
- Top 20 Backtracking Algorithm Interview Questions
- Magnet Puzzle | Backtracking-9
- Backtracking to find all subsets
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.