https://leetcode.com/problems/gray-code/

class Solution {
    func toD2(_ n: Int) -> [Int] {
        if n == 2 {
            return [0, 1, 3, 2]
        } else {
            return toD2(n-1) + toD2(n-1).map{ 2<<(n-2) + $0 }.reversed()
        }
    }
    func grayCode(_ n: Int) -> [Int] {
        if n == 0 {
            return [0]
        } else if n == 1 {
            return [0, 1]
        } else {
            return toD2(n)
        }
    }
}

Runtime: 12 ms, faster than 100.00% of Swift online submissions for Gray Code.
Memory Usage: 19 MB, less than 40.00% of Swift online submissions for Gray Code.