Gray Code (镜像反射法,图解)
镜像反射法(动态规划)
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1,0);
int head=1;
for(int i=0;i<n;i++){
for(int j=res.size()-1;j>=0;j--)
res.push_back(head+res[j]);
head<<=1;
}
return res;
}
};
流程打印
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1,0);
int head=1;
for(int i=0;i<n;i++){
for(int j=res.size()-1;j>=0;j--){
res.push_back(head+res[j]);
cout<<*(res.cend()-1)<<" "<<"j= "<<j<<endl;}
head<<=1;
}
return res;
}
};
1 j=0
3 j=1
2 j=0
6 j=3
7 j=2
5 j=1
4 j=0