Very Simple C++ Solution with explanation

  • 0

    This is very straight forward.
    You can use the knowledge which you learned in topology class.

    Draw a dot which is 0-D where N is 0, name the dot as number {0}

    Draw a line which is 1-D where N is 1, name the dot as numbers {0, 1}

    Draw a rectangle which is 2-D where N is 2, name the dot as numbers {00, 01, 11, 10}

    Draw a cube which is 3-D where N is 3, name the dot as numbers {000, 001, 011, 010, 110, 111, 101, 100}

    Draw a 4-D hypercube where N is 4 ... (2 3-D cubes)

    Draw a 5-D hypercube... (4 3-D cubes)

    6-D... Ok... it's hard to draw 8 cubes in 6-D.... now we can find a pattern here.

    See? there is a pattern.

    vector<int> grayCode(int n) {
            if(n == 0) return {0};
            vector<int> ret = {0, 1};
            for(int i=2; i<=n; i++)
                for(int j=ret.size()-1; j>=0; j--)
            return ret;

Log in to reply

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