leetcode [89]Gray Code
The gray code is a binary numeral system where two successive values 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.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
题目大意:
给出数字n,生成n位的格雷码,并且生成序列的前一位和后面一位只一位不同。
解决方法:
我想的方法是就是顺着0,1,2,3...2^n-1顺着取,如果这个数没有被加入序列,而且这个数组和序列最后一位的异或得到的数1的位数只有一个,那么这个数字就可以被加入序列,但是如果这么按顺序查找的话,可能导致后面找不到这样的数满足要求,并不能得到满足要求的数组。
错误思想的java解法:
public class Solution { private boolean isRight(int a,int b){ int n=a^b; int count=0; while(n!=0){ n&=(n-1); count++; } return count==1; } public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); boolean[] visited = new boolean[(int) Math.pow(2, n)]; visited[0] = true; res.add(0); int i = 1; while (i < Math.pow(2, n)) { for (int j = 0; j < Math.pow(2, n); j++) { if (!visited[j] && isRight(res.get(res.size() - 1), j)) { res.add(j); visited[j] = true; break; } } i++; } return res; } }
看了一下别人的解决方法,有一个特别神奇,先将集合中添加0。然后循环n次,每一次想集合中添加2^i个元素,最后返回的集合含有2^n个元素。满足要求,而且这每一次添加的2^i个元素之间互异都会得到1,因为添加的2^i个元素是基于集合中已经有的元素进行操作的,而集合中已经有的元素满足互异条件。
比如当n=2时:
{(0)}
{(0)(1)}
{(00)(01)(11,10)}
当n=3时:
{(0)}
{(0)(1)}
{(00)(01)(11,10)}
{(000)(001)(011,010)(110,111,101,100)}
java:
public class Solution { public List<Integer> grayCode(int n) { List<Integer>res=new ArrayList<Integer>(); res.add(0); for(int i=0;i<n;i++){ int size=res.size(); for(int j=size-1;j>=0;j--){ res.add(res.get(j)|1<<i); } } return res; } }