首页 > 代码库 > 118. Pascal's Triangle

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

分析 第k层有k个元素,每层第一个及最后一个元素值为1,对于(k>2)层,第n(n>1 && n < k)个元素A[k][n] = A[k-1][n-1]+A[k-1][n];
 1 class Solution { 2 public: 3     vector<vector<int>> generate(int numRows) { 4         vector<vector<int>> vals; 5          6         vals.resize(numRows); 7          8         for(int i = 0; i < numRows; i++){ 9             vals[i].resize(i+1);10             vals[i][0] = 1;11             vals[i][vals[i].size()-1] = 1;12             for(int j = 1; j < vals[i].size()-1; j++){13                 vals[i][j] = vals[i-1][j-1]+vals[i-1][j];14             }15         }16         return vals;17     }18 };

 

118. Pascal's Triangle