c++ recursive code


  • 0
    E
    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> res;
            int a = 0;
            res.push_back(a);
            for (int i = 0; i < n; i++)
                next(a, res, i, n);
            return res;
        }
        
        void next(int &a, vector<int> &res, int begin, int n) {
            if (begin==n || begin < 0)
                return;
            
            a = a ^ (1<<begin);
            res.push_back(a);
            for (int i = 0; i < begin; i++)
                next(a, res, i, n);
    
        }
    };
    

Log in to reply
 

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