标签:
[0,1,3,2]
. Its gray code sequence is:00 - 0 01 - 1 11 - 3 10 - 2
[0,2,3,1]
is also a valid gray code sequence according to the above definition.
思路:
例举grey code序列,并找规律 :
public class Solution { public List<Integer> grayCode(int n) { List<Integer> result = new LinkedList<>(); if(n<0) return result; result.add(0); int inc = 1; for (int i = 0; i < n; i++) { int size = result.size(); for(int j=size-1;j>=0;j--) { result.add(result.get(j)+inc); } inc = inc<<1; } return result; } }
解法二:O(n)
public class Solution { public List<Integer> grayCode(int n) { List<Integer> result = new LinkedList<>(); for (int i = 0; i < 1<<n; i++) result.add(i ^ i>>1); //1<<n = 2^n return result; } }
reference:
http://bangbingsyb.blogspot.com/2014/11/leetcode-gray-code.html
标签:
原文地址:http://www.cnblogs.com/hygeia/p/5180874.html