Shortest C++ code with 5ms


  • 0
    C
    class Solution {
    public:
        vector<int> grayCode(int n) {
            int index = 1;
            vector<int> result;
            result.push_back(0);
            if(n == 0) return result;
            result.push_back(1);
            
            for (int i = 1; i < n; i++) {
                while(index != -1) result.push_back((1<<i) | result[index--]);
                index = result.size()-1;
            }
            
            return result;
        }
    };

  • 0
    P
    vector<int> grayCode(int n) {
        vector<int> ans;
        int total = 1<<n;
        for (int cnt = 0;cnt < total;++cnt)
            ans.push_back(cnt >> 1 ^ cnt);
        return ans;
    }

Log in to reply
 

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