Divide and conquer!
Add a leading 0 or 1 bit to your existing results so here comes two sub-results: 0{xxxxx} and 1{xxxxx}. How to merge them? Just keep the first sub group and append the second group items reversely so that there is only a 1-bit difference between the end of group 0 and “start” of group 2.
class Solution {
public:
vector<int> grayCode(int n) {
if (n == 0)
return { 0 };
vector<int> results = { 0, 1 };
for (size_t i = 1; i < n; ++i)
{
for (int j = results.size() - 1; j >= 0; --j)
{
results.push_back(results[j] + (1 << i));
}
}
return results;
}
};