Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]


Analyse: Considering numRows =0 , 1, 2 and other circumustance.

 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         vector<vector<int> > result;
 5         if(numRows == 0) return result;
 6        
 7         vector<int> row0;
 8         row0.push_back(1);
 9         result.push_back(row0);
10         if(numRows == 1) return result;
11         
12         row0.push_back(1);
13         result.push_back(row0);
14         if(numRows == 2) return result;
15         
16         for(int i = 3; i <= numRows; i++){
17             vector<int> row;
18             vector<int> previous = result[result.size()-1];
19             row.push_back(1);
20             for(int j = 1; j < i - 1; j++){
21                 row.push_back(previous[j-1] + previous[j]);
22             }
23             row.push_back(1);
24             result.push_back(row);
25         }
26         return result;
27     }
28 };

 

你可能感兴趣的:(pascal)