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].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gray-code
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给定一个数字n,代表一个二进制数的位数。给出位数为n的二进制数字的所有数值,要求有序,序列为每个相邻的数字,其二进制数只有一个位是不一样的。
思路:
n为0:
0
n为1:
0
1
n为2:
00
01
11
10
n为3
000
001
011
010
110
111
101
100
留意到,每次递增,则列表是原来的两倍,且是对前面答案的镜像,然后再往后面加二进制中的1。
相当于,当n=2到n=3时,就是把n=2的答案,从后到前遍历,得到的数字加上2^2,放入数组中。
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> ans = new ArrayList<Integer>((int) Math.pow(2,n));
ans.add(0);
for (int i = 0; i < n; i++) {
int len = ans.size();
int plus = (int) Math.pow(2, i);
for (int j = len - 1; j >= 0; j--) {
ans.add(ans.get(j) + plus);
}
}
return ans;
}
}
368

被折叠的 条评论
为什么被折叠?



