题目:
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.
解题思路:
001
011
010
110
111
101
100
class Solution {
public:
vector<string> getGray(int n){
vector<string> gray(pow(2,n));
if(n==1)
{
gray[0] = "0";
gray[1] = "1";
return gray;
}
else
{
vector<string> before = getGray(n-1);
for(int i=0;i<before.size();i++)
{
gray[i] = "0"+before[i];
gray[pow(2,n)-1-i] = "1"+before[i];
}
return gray;
}
}
int biTodec(string s){
int ans = 0;
for(int i=0;i<s.size();i++)
ans = 2*ans + (s[i]-'0');
return ans;
}
vector<int> grayCode(int n) {
vector<int> res;
if(n==0)
{
res.push_back(0);
return res;
}
vector<string> gray = getGray(n);
for(int i=0;i<gray.size();i++)
res.push_back(biTodec(gray[i]));
return res;
}
};