leetcode-119-Pascal's Triangle II(生成某一行的帕斯卡三角形)

题目描述:

 

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

 

要完成的函数:

vector<int> getRow(int rowIndex) 

 

说明:

1、这道题给定一个行数rowIndex,要求返回给定行数那一行的帕斯卡三角形,结果存储在vector中。要求空间复杂度不超过O(rowIndex)。

2、做了前面的帕斯卡三角形的生成那道题目,实现这道题目也就易如反掌了。

同样的方法,我们逐行生成每一行的帕斯卡三角形,到达指定行数时,停下来,返回vector就可以了。

代码如下:

    vector<int> getRow(int rowIndex) 
    {
        vector<int>res={1};
        int i;
        while(rowIndex--)//如果rowIndex==0,那么不会进入循环,如果rowIndex==1,进入循环一次。
        {//while(rowIndex--)这种写法,是先判断rowIndex是不是0,如果不是那么进入循环,最后再减一;如果是,那么不进入循环。
            i=res.size()-1;
            while(i>0)
            {
                res[i]=res[i]+res[i-1];
                i--;
            }
            res.push_back(1);
        }
        return res;
    }

上述代码实测3ms,beats 80.79% of cpp submissions。

原文地址:https://www.cnblogs.com/chenjx85/p/9104105.html