My dp solution with c++


  • 0
    B
    class Solution {
    public:
        vector<int> grayCode(int n) {
            if ( n == 0 ) {
                vector<int> v;
                v.push_back(0);
                return v;
            }
            vector<int> F[n+1];
            vector<int> v;
            v.push_back(0);
            v.push_back(1);
            F[1] = v;
            for ( int i = 2; i < n+1; i++ ) {
                for ( int j = 0; j < F[i-1].size(); j++ )
                    F[i].push_back(F[i-1][j]);
                for ( int j = F[i-1].size()-1; j >= 0 ; j-- ) 
                    F[i].push_back(F[i-1][j] + 1 << (i-1) );
            }
            return F[n];
        }
    };

Log in to reply
 

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