letecode [118] - Pascal's Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
 

Subject to the effect:

  Pascal's Triangle n rows before output, expressed as a two-dimensional vector.

Understanding:

  2-line results before initialization. 3-n of the line, using the accumulated previous row obtained.

Code C ++:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> vec;
        if(numRows==0) return vec;
        vector<int> rowVec;
        rowVec.push_back(1);
        vec.push_back(rowVec);
        if(numRows==1) return vec;
        rowVec.push_back(1);
        vec.push_back(rowVec);
        if(numRows==2) return vec;  
        int i=3;
        while(i<=numRows){
            rowVec.clear();
            rowVec.resize(i);
            rowVec[0] = 1;
            int j = 1;
            while(j<i-1){
                rowVec[j] = vec[i-2][j-1] + vec[i-2][j];
                ++j;
            }
            rowVec[i-1] = 1 ; 
            vec.push_back (rowVec); 
            ++ i; 
        } 
        Return thing; 
    } 
};

operation result:

  When executed with:  0 MS   memory consumption:  8.8 MB

Guess you like

Origin www.cnblogs.com/lpomeloz/p/10994864.html