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]
]

New version!
 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         vector<vector<int> > result;
 5         if(numRows < 1) return result;
 6         
 7         for(int i = 0; i < numRows; i++){
 8             vector<int> temp;
 9             for(int j = 0; j <= i; j++){
10                 if(j == 0 || j == i)
11                     temp.push_back(1);
12                 else
13                     temp.push_back(result[i - 1][j - 1] + result[i - 1][j]);
14             }
15             result.push_back(temp);
16         }
17         return result;
18     }
19 };


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 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4421962.html