```
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res;
res.push_back(0);
if(n==0) return res;
res.push_back(1);
stack<int> s;
s.push(0);
s.push(1);
int factor=2;
while(n!=1){
while(!s.empty()){
int temp=s.top()+factor;
s.pop();
res.push_back(temp);
}
for(int i=0;i<res.size();i++) s.push(res[i]);
factor=factor*2;
n--;
}
return res;
}
};
```