LeetCode Pascal's Triangle II

来源:互联网 发布:qq群关系数据库 种子 编辑:程序博客网 时间:2024/06/05 14:42

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?

    第0层为1,第1层为1 1,第2层为1 2 1,第3层为1 3 3 1,从第2层到第3层,a[0]=1不变,a[1]=原a[0]+a[1],a[2]=原a[1]+a[2],a[3]为添加进去的1,于是,可以用动态规划的思想,从第i层到第i+1层,a[0]=1不变,a[1]=原a[0]+a[1]...a[k]=原a[k-1]+a[k],最后在数组尾添加元素1。


class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res;        res.push_back(1);        int cur,pre;        for(int i=1;i<=rowIndex;i++){            pre=res[0];            for(int j=1;j<res.size();j++){                cur=res[j];                res[j]+=pre;                pre=cur;            }            res.push_back(1);        }        return res;    }};

0 0
原创粉丝点击