pascals-triangleI、II——生成规律的三角形

1、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]
]
res[i][j]=res[i-1][j-1]+res[i-1][j]
 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         vector<vector<int>> res;
 5         if(numRows==0) return res;
 6         for(int i=0;i<numRows;i++){
 7             vector<int> tmp;
 8             if(i==0){
 9                 tmp.push_back(1);
10                 res.push_back(tmp);
11                 continue;
12             }
13             for(int j=0;j<=i;j++){
14                 if(j==0||j==i){
15                     tmp.push_back(1);
16                     continue;
17                 }
18                 
19                 tmp.push_back(res[i-1][j-1]+res[i-1][j]);
20             }
21             res.push_back(tmp);
22         }
23         return res;
24     }
25 };

 2、

Given an index k, return the k th 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?这道题跟Pascal's Triangle很类似,只是这里只需要求出某一行的结果。Pascal's Triangle中因为是求出全部结果,所以我们需要上一行的数据就很自然的可以去取。而这里我们只需要一行数据,就得考虑一下是不是能只用一行的空间来存储结果而不需要额外的来存储上一行呢?这里确实是可以实现的。对于每一行我们知道如果从前往后扫,第i个元素的值等于上一行的res[i]+res[i+1],可以看到数据是往前看的,如果我们只用一行空间,那么需要的数据就会被覆盖掉。所以这里采取的方法是从后往前扫,这样每次需要的数据就是res[i]+res[i-1],我们需要的数据不会被覆盖,因为需要的res[i]只在当前步用,下一步就不需要了。这个技巧在动态规划省空间时也经常使用,主要就是看我们需要的数据是原来的数据还是新的数据来决定我们遍历的方向。时间复杂度还是O(n^2),而空间这里是O(k)来存储结果,仍然不需要额外空间。代码如下:

 1 class Solution {
 2 public:
 3     vector<int> getRow(int rowIndex) {
 4         
 5         if(rowIndex<0) return vector<int>();
 6         vector<int> res(rowIndex+1,1);
 7         for(int i=0;i<=rowIndex;i++){
 8             for(int j=i-1;j>=1;j--){
 9                 res[j]=res[j]+res[j-1];
10             }
11         }
12         return res;
13     }
14 };
原文地址:https://www.cnblogs.com/zl1991/p/7001872.html