119. Pascal's Triangle II(easy)

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/88391781

Easy

419153FavoriteShare

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.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

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

Follow up:

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

C++:

扫描二维码关注公众号,回复: 5490713 查看本文章
/*
 * @Author: SourDumplings
 * @Link: https://github.com/SourDumplings/
 * @Email: [email protected]
 * @Description: https://leetcode.com/problems/pascals-triangle-ii/
 * @Date: 2019-03-11 11:47:19
 */

class Solution
{
  public:
    vector<int> getRow(int rowIndex)
    {
        ++rowIndex;
        vector<int> res(rowIndex), temp(rowIndex);
        for (int i = 0; i < rowIndex; i++)
        {
            copy(res.begin(), res.end(), temp.begin());
            for (int j = 0; j < i + 1; j++)
            {
                if (j == 0 || j == i)
                {
                    res[j] = 1;
                }
                else
                {
                    res[j] = temp[j] + temp[j - 1];
                }
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/88391781