Pascal's Triangle,Pascal's Triangle II

一.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]
]
class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> res;
        if(numRows==0){
            return res;
        }
        vector<int> row;
        int size = 0;
        while(numRows--){
            int x = 1;for(int i=1;i<size;i++){
                int y = row[i];
                row[i]= x+y;
                x = y;
            }
            row.push_back(1);
            res.push_back(row);
            size++;
        }
        return res;
    }
};

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

class Solution {
public:
    vector<int> getRow(int rowIndex) {
         rowIndex+=1;
         vector<int> row;
         int size = 0;
         while(rowIndex--){
             int x = 1;
             for(int i=1;i<size;i++){
                 int y = row[i];
                 row[i] = x+y;
                 x=y;
             }
             row.push_back(1);
             size++;
         }
         return row;
    }
};
原文地址:https://www.cnblogs.com/zengzy/p/4989654.html