Pascal's Triangle,Pascal's Triangle II

喜夏-厌秋 提交于 2020-01-11 02:29:54

一.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;
    }
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!