Straightforward 0ms C++ answer


  • 0
    B

    All answers will look the same but I'm posting mine anyway ;)

    For reference I went from 4ms to 0ms by resizing my tmp array and inserting into it by indexing into it in the inner loop, instead of clearing it and pushing_back into it.

    class Solution {
    public:
        typedef std::vector<int> IntVec;
        
        vector<vector<int>> generate(int numRows) {
            
            std::vector<IntVec> ret;
            if (numRows < 1) {
                return ret;
            }
        
            IntVec vec;
            vec.push_back(1);
            ret.push_back(vec);
        
            for (int j = 1; j < numRows; ++j) {
                vec.resize(j+1);
        
                vec[0] = 1;
                for (int i = 1; i < j; ++i) {
                    vec[i] = ret[j-1][i-1] + ret[j-1][i];
                }
                vec[j] = 1;
    
                ret.push_back(vec);
            }
            
            return ret;
    
        }
    };

Log in to reply
 

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