[Leetcode] Pascal's Triangle II

来源:互联网 发布:古明地觉知夏天的日子 编辑:程序博客网 时间:2024/06/03 20:46

描述

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?

分析

给定 n 返回杨辉三角的第 n 行。

仿照 前一题 [Pascal’s Triangle] 的思路进行构造。由于这里不需要返回前 n 行而只需要第 n 行,因此可以共用一个向量,每次将杨辉三角的下一行赋值给这个向量,直到第 n 行,这样空间复杂度为 0(n)

代码

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res(rowIndex + 1, 0);        for (int i = 0; i <= rowIndex; i++) {            res[0] = res[i] = 1;            for (int j = i - 1; j > 0; j--)                res[j] += res[j - 1];        }        return res;    }};
0 0
原创粉丝点击