First, the array --- Pascal's Triangle

Given a non-negative integer numRows, generation ago with numRows Yang Hui Triangle.

 

 

In Pascal's Triangle, each number is the number of its top left and top right and.

Example:

Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

 

Thinking 

Each row is an end to end, each row can be initialized to all 1, then calculating a modified

Code:

. 1  class Solution {
 2  public :
 . 3      Vector <Vector < int >> Generate ( int numRows) {
 . 4          // define an empty array, for storing each row of Pascal's triangle - small array 
. 5          Vector <Vector < int >> RES;
 . 6          // first two lines are the default array 
. 7          IF (numRows <= 2 ) {
 . 8              for ( int I = 0 ; I <numRows; I ++ ) {
 . 9                  Vector < int > Small (I + . 1 , . 1 ); / /1 has a first line 1, the second row has two 1 
10                  res.push_back (Small); // will be credited to the first two rows of empty array res 
. 11              }
 12 is              return res; // res contains Pascal's triangle the first two lines 
13 is          }
 14          the else {
 15              res = Generate (numRows- . 1 ); // get the res array numRows-1 front row 
16              Vector < int > newsmall (numRows, . 1 ); // initialize the first row numsRow
 17              @ numRows-1 from the first row to obtain a first calculated with numRows first numRows-1 line array index res-2 numRows 
18 is              for ( int J = 0;j<res[numRows-2].size()-1;j++){
19                 newsmall[j+1] = res[numRows-2][j] + res[numRows-2][j+1];
20             }
21             res.push_back(newsmall);
22         }
23         return res;
24     }
25 };

 

Guess you like

Origin www.cnblogs.com/pacino12134/p/10991329.html