恰好y总讲过
https://www.acwing.com/video/554/
之后就把字符串转成数字就好了
class Solution {
public:
typedef unsigned long long ULL;
vector<int> grayCode(int n) {
if(n==0) return {0};
vector<int> res;
for(int i=0;i<1<<n;i++){
string ans=f(n,i);
res.push_back(change(ans,n));
}
return res;
}
string f(ULL n, ULL k)
{
if (!n) return "";
if (k < (1ull << n - 1)) return "0" + f(n - 1, k);
ULL t = (1ull << n) - 1;
if (n == 64) t = -1;
return "1" + f(n - 1, t - k);
}
int change(string s,int n){
int a=0;
for(int i=0;i<n;i++){
if((s[i]-'0')&1){
a+=1<<(n-i-1);
}
}
return a;
}
};