Leetcode

Gray Code

  • Time:O(2^n)
  • Space:O(2^n)

C++

class 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;
  }
};

JAVA

class 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;
  }
}

Python

class 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