题目:
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 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.
思路:
总结该题目的规律:假设对于(n-1)而言,我们已经计算出来了gray code的序列grayCode(n-1),那么对于n而言,一个可行的办法是什么呢?由于grayCode(n)中的每个元素都有n个二进制位,所以我们可以将grayCode(n)分为两部分,第一部分是首位为0的元素,第二部分是首位位1的元素。可以发现,其中第一部分恰好就是grayCode(n-1)中的元素。那么如果我们依次将第一部分的元素首位都变成1,然后逆序加入序列,不就构成了grayCode(n)的结果吗?下面的代码正是这一思路的结果,我们用递归实现了这一算法。
代码:
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result = {0};
if (n == 0) {
return result;
}
else if (n == 1)
{
result.push_back(1);
return result;
}
result = grayCode(n-1);
int half_size = result.size();
int added_value = 1 << (n - 1);
for(int i = half_size - 1; i >= 0; --i) {
result.push_back(added_value + result[i]);
}
return result;
}
};