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

Pascal's Triangle

时间:2014-08-14 23:50:36      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   div   代码   amp   

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

思路:对于Pascal三角形的第i行,其两端元素为1,而中间元素Pascal[i][k]=Pascal[i][k-1]+Pascal[i][k]。

 1 class Solution {
 2 public:
 3     vector<vector<int>> generate( int numRows ) {
 4         if( numRows <= 0 ) { return vector<vector<int>>(0); }
 5         vector<vector<int>> pascals( numRows );
 6         pascals[0].resize( 1, 1 );
 7         for( int i = 1; i < numRows; ++i ) {
 8             pascals[i].resize( i+1, 1 );
 9             for( int k = 1; k < i; ++k ) {
10                 pascals[i][k] = pascals[i-1][k-1] + pascals[i-1][k];
11             }
12         }
13         return pascals;
14     }
15 };

另外,Pascal三角形的每一行是对称的,我们可以将上述算法的内层循环进行修改以优化代码。

 1 class Solution {
 2 public:
 3     vector<vector<int>> generate( int numRows ) {
 4         if( numRows <= 0 ) { return vector<vector<int>>(0); }
 5         vector<vector<int>> pascals( numRows );
 6         pascals[0].resize( 1, 1 );
 7         for( int i = 1; i < numRows; ++i ) {
 8             pascals[i].resize( i+1, 1 );
 9             for( int k = 1; k <= i/2; ++k ) {
10                 pascals[i][k] = pascals[i][i-k] = pascals[i-1][k-1] + pascals[i-1][k];
11             }
12         }
13         return pascals;
14     }
15 };

 

Pascal's Triangle,布布扣,bubuko.com

Pascal's Triangle

标签:style   blog   color   io   for   div   代码   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3913530.html

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