## [leetcode.com]算法题目 - 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]
]
 1 class Solution {
2 public:
3     vector<vector<int> > generate(int numRows) {
4         // Start typing your C/C++ solution below
5         // DO NOT write int main() function
6         if(0 == numRows){
7             vector<vector<int> > result;
8             return result;
9         }
10
11         vector<vector<int> > result(numRows);
12
13         vector<int> first(1,1);
14         result[0] = first;
15         for(int i=1;i<numRows;i++){
16             result[i] = nextTriangle(result[i-1]);
17         }
18
19         return result;
20     }
21
22     vector<int> nextTriangle(vector<int> a){
23         int k = a.size();
24         vector<int> next(k+1);
25         for(int i=0;i<k+1;i++){
26             if(0==i){
27                 next[i] = a[i];
28                 continue;
29             }
30             if(k==i){
31                 next[i] = a[k-1];
32                 continue;
33             }
34             next[i] = a[i-1]+a[i];
35         }
36         return next;
37     }
38 };

posted on 2013-09-12 20:53  Horstxu  阅读(169)  评论(0编辑  收藏  举报