[C++] iterative


  • 0
    4
     vector< vector< int > > generate( int numRows ) 
        {
            vector< vector< int > > out;
            if( numRows )
            {
                vector< int > temp = {1};
                out.push_back( temp );
                if( numRows > 1 )
                {
                    temp.push_back( 1 );
                    out.push_back( temp );
                    
                    
                    for( int i = 2; i < numRows; ++i )
                    {
                        temp.clear();
                        temp.resize( i + 1 );
                        temp[0] = 1;
                        for( int j = 0; j < ( i + 1 ) / 2; ++j )   // fill 1st half
                        {
                            temp[j + 1] = out[i - 1][j] + out[i - 1][j + 1];
                        }
                        for( int j = 0; j < i / 2; ++j )            // reflect 2nd half
                        {
                            temp[i - j] = temp[j];
                        }
                        out.push_back( temp );
                    }
                }
            }
            return out;
        }

Log in to reply
 

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