题目描述:
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+1位,
- 首先第一位为0的2^n种,除在最前面多加一个零外其余与n位的情况相同;
- 然后是第一位为1的2^n种,是最前面一位加1和n位时的逆排列的组合
比如由两位格雷码到三位
//两位的格雷码
00
01
11
10
//三位的格雷码
000
001
011
010//这四个就是两位的格雷码直接在最前面加零获得,对应的十进制的值不变
100
101
111
110//这四个就是两位的格雷码逆序排列后在最前面加1获得,对应的十进制是在原值的基础上加pow(2,3-1)
知道了这个算法实现就非常简单了
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
if(n < 0)return res;
res.push_back(0);
if(n == 0)return res;
for(int i = 0; i < n; i ++){
int suanz = pow(2,i);
for(int j = suanz - 1; j >= 0; j --)
res.push_back(suanz + res[j]);
}
return res;
}
};