The gray code is a binary numeral system where the successive values are differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code . A Gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00-001-111-310-2
Note:
For a given n, a gray code sequence is not uniquely defined.
For example, was [0,2,3,1]
also a valid gray code sequence according to the above definition.
For now, the judge are able to judge based on one instance of gray code sequence. Sorry about that.
This problem is not difficult, mainly to grasp what is gray code, and then to do this problem, the specific gray code concept reference Baidu can, the specific solution is to traverse, one-to-test can be.
The code is as follows:
public class Solution {public list<integer> graycode (int n) { list<integer> List = new arraylist< Integer> (); Remove duplicate set<string> Set = new hashset<string> (); Array representing binary number char[] c = new Char[n]; Arrays.fill (c, ' 0 ');//All 0 set.add (new String (c)); List.add (0); int i = 1;//starting from 1 //Gray code length int len = (int) Math.pow (2, n); while (i++ < len) { //try each for (int j = c.length-1; J >= 0; j--) { c[j] = c[j] = = ' 1 '? ' 0 ': ' 1 ';//each bit is different or string b = new string (c); Success adds the result set and ends the loop if (Set.add (b)) { //binary conversion to decimal List.add (integer.valueof (b, 2)); break; } else{ //If the value is not converted back c[j] = c[j] = = ' 1 '? ' 0 ': ' 1 '; } } } return list; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 89.Gray Code (gray code) thinking and methods of solving problems