Simple DFS solution (c++)


  • 0
    Z
    class Solution {
    public:
        void dfs(int start, int n, int &num, vector<int> &res) {
            if (start > n) return;
            dfs(start + 1, n, num, res);
            num ^= (1 << (n - start));
            res.push_back(num);
            dfs(start + 1, n, num, res);
        }
        
        vector<int> grayCode(int n) {
            vector<int> res;
            res.push_back(0);
            int num = 0;
            dfs(1, n, num, res);
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.