My c++ 4ms easy-to-understand solution


  • 1

    // Take a look at the test cases, you will notice that the result of n is just the result of n-1 + shift 1 at the nth position to the left(1<<n-1), and then do AND operation with all the elements in result of n-1. Therefore, we can complete it using iteration.

    public:
        vector<int> grayCode(int n) {
            
            if (n == 0) return{0};
            vector<int> result;
            result.push_back(0);
            result.push_back(1);
            for (int i = 1; i < n; i++) {
                for (int j = pow(2,i)-1; j>=0; --j) {
                    result.push_back(result[j] | (1<<i));
                }
            }
            return result;
        }
    };

Log in to reply
 

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