码迷,mamicode.com
首页 > 其他好文 > 详细

Pascal's Triangle

时间:2015-04-13 14:34:42      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

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


Analyse: Considering numRows =0 , 1, 2 and other circumustance.

 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         vector<vector<int> > result;
 5         if(numRows == 0) return result;
 6        
 7         vector<int> row0;
 8         row0.push_back(1);
 9         result.push_back(row0);
10         if(numRows == 1) return result;
11         
12         row0.push_back(1);
13         result.push_back(row0);
14         if(numRows == 2) return result;
15         
16         for(int i = 3; i <= numRows; i++){
17             vector<int> row;
18             vector<int> previous = result[result.size()-1];
19             row.push_back(1);
20             for(int j = 1; j < i - 1; j++){
21                 row.push_back(previous[j-1] + previous[j]);
22             }
23             row.push_back(1);
24             result.push_back(row);
25         }
26         return result;
27     }
28 };

 

Pascal's Triangle

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4421962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!