Pascal's Triangle II c++

来源:互联网 发布:docker hub ubuntu 编辑:程序博客网 时间:2024/05/16 16:07

原题目:

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?

这里主要讨论空间复杂度为O(K)的解法。由于我们只用一行空间,所以采用在每一行从后往前顺序去计算每一行的元素值。


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


原创粉丝点击