LeetCode:Pascal's Triangle I II

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

分析:简单的模拟从第一层开始计算即可

 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         vector<vector<int> >res;
 7         if(numRows == 0)return res;
 8         res.push_back(vector<int>{1});
 9         if(numRows == 1)return res;
10         vector<int>tmp;
11         tmp.reserve(numRows);
12         for(int i = 2; i <= numRows; i++)
13         {
14             tmp.clear();
15             tmp.push_back(1);
16             for(int j = 1; j < i-1; j++)
17                 tmp.push_back(res[i-2][j-1]+res[i-2][j]);
18             tmp.push_back(1);
19             res.push_back(tmp);
20         }
21         return res;
22     }
23 };

LeetCode:Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

分析:每次计算只和上一层有关系,因此只需要一个数组空间就可以                                                                                                            本文地址

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         vector<int> res(rowIndex+1,1);
 7         if(rowIndex == 0)return res;
 8         for(int i = 1; i <= rowIndex; i++)
 9         {
10             int tmp = res[0];
11             for(int j = 1; j <= i-1; j++)
12             {
13                 int kk = res[j];
14                 res[j] = tmp+res[j];
15                 tmp = kk;
16             }
17         }
18         return res;
19     }
20 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3436562.html

原文地址:https://www.cnblogs.com/TenosDoIt/p/3436562.html