[LeetCode 118] - 杨辉三角形(Pascal's Triangle)

问题

给出变量numRows,生成杨辉三角形的前numRows行。

例如,给出numRows=5,返回:

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 

初始思路

基本算法和 杨辉三角形II(Pascal's Triangle II) 的基本一致。每算完一行的值将这些值拷贝一份到vector中即可。代码如下:

 1 class Solution {
 2     public:
 3         std::vector<std::vector<int> > generate(int numRows)
 4         {
 5             std::vector<std::vector<int> > result;
 6             
 7             std::vector<int> columnInfo;
 8             
 9             if(numRows == 0)
10             {
11                 return result;
12             }
13             
14             columnInfo.push_back(1);
15             result.push_back(columnInfo);
16             
17             if(numRows == 1)
18             {
19                 return result;
20             }
21             
22             columnInfo.push_back(1);
23             
24             
25             for(int i = 1; i < numRows; ++i)
26             {
27                 for(int j = i; j > 0; --j)
28                 {
29 //第一列和最后一列永远为1,不需要进行处理
30                     if(j != 0 && j != i)
31                     {
32                         columnInfo[j] = columnInfo[j - 1] + columnInfo[j];
33                     }
34                 }
35                         
36                 result.push_back(columnInfo);
37 //下一行开始列数相应增加,且最后一列的数字肯定是1
38                 columnInfo.push_back(1);
39 
40             }
41             
42             return result;
43         }
44     };
generate

 

posted @ 2013-07-02 23:55  Shawnone  阅读(287)  评论(0编辑  收藏  举报