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

]

题解:一A的简单题,按照定义生成向量即可。代码如下:

 1 class Solution {

 2 public:

 3     vector<vector<int> > generate(int numRows) {

 4         vector<vector<int> > answer;

 5         if(numRows == 0)

 6             return answer;

 7         vector<int> temp(1,1);

 8         answer.push_back(temp);

 9         

10         for(int i = 1;i <= numRows - 1;i++){

11             vector<int> last(answer[i-1]);

12             vector<int> v(1,1);

13             for(int j = 1;j <= i-1;j++){

14                 v.push_back(last[j-1]+last[j]);

15             }

16             v.push_back(1);

17             answer.push_back(v);

18         }

19         return answer;

20     }

21 };

这里积累一下vector的各种初始化方式:

vector<T>  v1; vector保存类型为T的对象。默认构造函数v1为空。
vector<T> v2(v1); v2是v1的一个副本。
vector<T> v3(n, i); v3包含n个值为i的元素。
vector<T> v4(n); v4含有值初始化的元素的n个副本。

上述代码中分别用到了前三种初始化方法。

 

 

你可能感兴趣的:(LeetCode)