No bit manipulation required 3ms C++


  • 0
    M
    • Go from the most left bit to the right.
    • The number of grey code is 2^n
    • Divide 2^n to half
    • For the first half, the next bit's first half will be 0 and the second half will be 1.
    • For the second half, the next bit's first half will be 1 and the second half will be 0.
    class Solution {
    private:
        void rec(int start_i, int end_i, int zero_or_one_first, int power, vector<int>* result) {
            if (power < 0) return;
            int mid = (start_i + end_i) / 2;
            int add = (int) pow(2, power);
            if (zero_or_one_first == 0) {
                for (int i = mid+1; i <= end_i; i++) (*result)[i] += add;
            } else {
                for (int i = start_i; i <= mid; i++) (*result)[i] += add;
            }
            rec(start_i, mid, 0, power-1, result);
            rec(mid+1, end_i, 1, power-1, result);
        }
    public:
        vector<int> grayCode(int n) {
            vector<int> result((int) pow(2, n), 0);
            rec(0, (int) pow(2, n) - 1, 0, n-1, &result);
            return result;
        }
    };
    

Log in to reply
 

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