C++ recursive and iterative


  • 0
    X
    class Solution {
    public:
    // iterative
        vector<int> grayCode(int n) {
            vector<int> vec{0};
            for(int i = 0; i < n; ++i){
                int tmp = 1 << i;
                for(int j = vec.size() - 1; j >= 0; --j){
                    vec.push_back(vec[j] + tmp);
                }
            }
            return vec;
        }
    /* recursive
        vector<int> grayCode(int n) {
            if(n == 0){
                return vector<int>{0};
            }
            vector<int> pre = grayCode(n - 1);
            vector<int> ans(pow(2, n));
            for(int i = 0; i < pre.size(); ++i){
                int tmp = pre[i];
                ans[i] = tmp;
                ans[ans.size() - 1 - i] = tmp + (1 << (n - 1));
            }
            return ans;
        }
    */
    };

Log in to reply
 

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