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=k时就是n=k-1的前面加上0或者1
dp[k]=dp[k-1]|1<<n, 2^(n-1) =< k< 2^n
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
res.push_back(0);
for(int i = 0;i<n;i++)
{
for(int j = res.size()-1;j>=0;--j)
{
res.push_back(res[j]|1<<i);
}
}
return res;
}
};