Share my iteration solution


  • -1
    S

    an iterative solution, just simulate the gray code produce process. 36ms
    Can adapt the other gray produce process easily.

    // iterative solution
    vector<int> grayCode(int n) {
        vector<int> ans;
        if (n < 1) {
            ans.push_back(0);
            return ans;
        }
        
        for (int i = 1; i <= n; ++i) {
            if (i == 1) {
                ans.push_back(0);
                ans.push_back(1);
                continue;
            }
            
            ans.insert(ans.end(), ans.rbegin(), ans.rend());
            int m = ans.size() / 2;
            for(int j = m; j < 2*m; ++j) {
                ans[j] += 1 << (i-1);
            }
        }
        
        return ans;
    }

  • 0
    S

    modified to be more concise

    // iterative solution
    vector<int> grayCode(int n) {
        vector<int> ans;
        ans.push_back(0);
        
        for (int i = 0; i < n; ++i)
            for (int j = ans.size()-1; j >= 0; --j)
                ans.push_back(ans[j] + (1 << i));
        
        return ans;
    }

Log in to reply
 

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