题目:
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(n)。这里我们可以根据杨辉三角的定义,逐行计算。顺序从左到右或者从右到左都可以。但是从右到左会更加简单一些。
代码:
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res(rowIndex + 1, 0); res[0] = 1; for (int i = 1; i <= rowIndex; ++i) { for (int j = i; j > 0; --j) { res[j] += res[j-1]; } } return res; } };