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=3,n=4的情况写在纸上,然后找规律。class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result(1, 0);
for (int i = 0; i < n; i++)
for (int j = (int)result.size() - 1; j >= 0; j--)
result.push_back(result[j] | (1 << i));
return result;
}
};
此外,对于解的规模为2^n的题目,一般思路都是每次把上一步得到的解“复制”一遍,每次解变成上一次的两倍。直接在“复制”的过程中动手脚即可。