【LeetCode】Pascal's Triangle (杨辉三角)

来源:互联网 发布:剪辑声音的软件 编辑:程序博客网 时间:2024/05/30 13:42
 

【LeetCode】Pascal's Triangle (杨辉三角)

分类: LeetCode 85人阅读 评论(0) 收藏 举报
leetcode

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

code :

[cpp] view plaincopy
  1. class Solution {  
  2. public:  
  3.     vector<vector<int> > generate(int numRows) {  
  4.         // Note: The Solution object is instantiated only once and is reused by each test case.  
  5.         vector<vector<int> > res;  
  6.         if(numRows == 0)  
  7.             return res;  
  8.         for(int i = 1; i <= numRows; i++)  
  9.         {  
  10.             vector<int> onelevel;  
  11.             onelevel.clear();  
  12.             onelevel.push_back(1);  
  13.             for(int j = 1; j < i; j++)  
  14.             {  
  15.                 onelevel.push_back(res[i-2][j-1] + (j < i-1 ? res[i-2][j] : 0));  
  16.             }  
  17.             res.push_back(onelevel);  
  18.         }  
  19.         return res;  
  20.     }  
  21. };  
原创粉丝点击