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.
For example, given n = 2, return
[0,1,3,2]
. Its gray code sequence is:00 - 0 01 - 1 11 - 3 10 - 2
Note:
For a given n, a gray code sequence is not uniquely defined.
For a given n, a gray code sequence is not uniquely defined.
For example,
[0,2,3,1]
is also a valid gray code sequence according to the above definition.
For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
Solution:
It is not hard to find the pattern of the gray code, gray[0]={0}, gray[1]=[0,1],gray[2]=[0"+"gray[1],1"+"gray[1].reverse()]=[00,01,11,10], gray[3]=[000,001,011,010; 110,111,101,100]. Here "+" kinda means concatenate eg. 1"+" 111= 1111. 0 "+" x= x, while 1 "+" x = 1*2^n +x, here n is the number of bits of the number. So the idea to get gray[n] is to reverse all gray[n-1] and add each number with 2^n, which is also the length of gray[n-1] and add the summation to the list of gray[n-1] one by one and the resulted list will be gray[n].
Time complexity: O(2^n) because the size of the result list will be expanded at exponential level.
Time complexity: O(2^n) because the size of the result list will be expanded at exponential level.
public List<Integer> grayCode(int n) {
List<Integer> res=new ArrayList<Integer>();
if(n<0) return res;
res.add(0);
for(int i=1;i<=n;i++){
int l=res.size();
for(int j=l-1;j>=0;j--){
res.add(res.get(j)+l);
}
}
return res;
}
No comments:
Post a Comment