89. Gray Code ¶ Time: $O(2^n)$ Space: $O(2^n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: vector<int> grayCode(int n) { vector<int> ans{0}; for (int i = 0; i < n; ++i) for (int j = ans.size() - 1; j >= 0; --j) ans.push_back(ans[j] | 1 << i); return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public List<Integer> grayCode(int n) { List<Integer> ans = new ArrayList<>(); ans.add(0); for (int i = 0; i < n; ++i) for (int j = ans.size() - 1; j >= 0; --j) ans.add(ans.get(j) | 1 << i); return ans; } } 1 2 3 4 5 6 7 8 9class Solution: def grayCode(self, n: int) -> list[int]: ans = [0] for i in range(n): for j in reversed(range(len(ans))): ans.append(ans[j] | 1 << i) return ans