pascals-triangle-i &ii

来源:互联网 发布:淘宝热卖商品排行榜 编辑:程序博客网 时间:2024/06/16 21:00

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?

class Solution {public:    vector<int> getRow(int rowIndex) {        if(rowIndex<0)            return vector<int>{};        vector<int> vecbef{1};          vector<int> veccur;        for(int i=1;i<=rowIndex;++i)            {                veccur.push_back(1);                for(int j=0;j<i-1;++j){                             veccur.push_back(vecbef[j]+vecbef[j+1]);                }                veccur.push_back(1);                vecbef=veccur;                veccur.clear();        }        return vecbef;    }};

题目描述

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) {        if(numRows<=0)            return vector<vector<int>>{};        vector<vector<int>> res;        vector<int> vecbef{1};          vector<int> veccur;        res.push_back(vecbef);        for(int i=2;i<=numRows;++i)            {                veccur.push_back(1);                for(int j=0;j<i-2;++j){                             veccur.push_back(vecbef[j]+vecbef[j+1]);                }                veccur.push_back(1);                vecbef=veccur;                res.push_back(vecbef);                veccur.clear();        }        return res;            }};
0 0
原创粉丝点击