leetcode 118

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

输出Pascal三角形的前n行;每次利用前面已经生成的行来生成下一行。

代码如下:
 1 class Solution {
 2 public:
 3     vector<vector<int>> generate(int numRows) {
 4         vector<vector<int>> pascal;
 5         vector<int> ss;
 6         if(numRows == 0)
 7         {
 8             return pascal;
 9         }
10         if(numRows == 1)
11         {
12             ss.push_back(1);
13             pascal.push_back(ss);
14             return pascal;
15         }
16         pascal.push_back({1});
17         for(int i = 1; i <numRows; i++)
18         {
19             for(int j = 0; j <= i; j++)
20             {
21                 if(j == 0 || j == i)
22                 {
23                     ss.push_back(1);
24                     continue;
25                 }
26                 int n = pascal[i-1][j-1] + pascal[i-1][j];
27                 ss.push_back(n);
28             }
29             pascal.push_back(ss);
30             ss.clear();
31         }
32         return pascal;
33     }
34 };

 

 
posted @ 2016-09-28 11:26  花椰菜菜菜菜  阅读(156)  评论(0编辑  收藏  举报