LeetCode: Pascal's Triangle II

来源:互联网 发布:捕鱼软件下载 编辑:程序博客网 时间:2024/06/05 14:21

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) {        vector<vector<int> >tri(rowIndex+1);        vector<int>res;        for(int i=0;i<rowIndex+1;++i)        {            tri[i].resize(i+1);        }        for(int i=0;i<rowIndex+1;++i)        {            tri[i][0] = 1;            tri[i][i] = 1;        }        for(int i=1;i<rowIndex+1;++i)        {            for(int j =1;j<i;++j)            {                tri[i][j] = tri[i-1][j-1]+tri[i-1][j];            }        }        for(int i = 0;i<rowIndex+1;++i)        {            int temp =tri[rowIndex][i];            res.push_back(temp);        }        return res;    }};
0 0