[LeetCode 题解]: 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         vector<int> vi;
 5         vector<vector<int> > ans;
 6         int i,j;
 7         vi.push_back(1);
 8         ans.clear();   // 注意初始化
 9         if(numRows<=0) return ans;
10         if(1==numRows)
11         {
12             ans.push_back(vi);
13             return ans;
14         }
15         if(2==numRows)
16         {
17             ans.push_back(vi);
18             vi.push_back(1);
19             ans.push_back(vi);
20             return ans;
21         }
22 
23         ans.push_back(vi);
24         vi.push_back(1);
25         ans.push_back(vi);
26         for(i=2;i<numRows;i++)
27         {
28             vi.clear();
29             vi.push_back(1);
30             for(j=1;j<i;j++)
31             {
32                 vi.push_back(ans[i-1][j-1]+ans[i-1][j]);
33             }
34             vi.push_back(1);
35             ans.push_back(vi);
36         }
37         return ans;
38     }
39 };

 转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!

posted @ 2014-05-05 15:39  Double_win  阅读(165)  评论(0编辑  收藏  举报