【一天一道LeetCode】#119. Pascal's Triangle II

来源:互联网 发布:pe远程控制软件 编辑:程序博客网 时间:2024/04/29 09:07

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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?

(二)解题

题目大意:求杨辉三角的第i行数。
和上题一样:【一天一道LeetCode】#118. Pascal’s Triangle.
只不过这题只需要返回第i行数。这里可以用两个vector,一个记录上一行的数,一个存储本行的数。
代码如下:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> pre;        vector<int> temp;        int n = 0;        while(n<=rowIndex)        {            temp.clear();            for(int i = 0 ; i < n+1 ; i++)            {                if(i==0||i==n) temp.push_back(1);//首尾为1                else temp.push_back(pre[i-1]+pre[i]);//其他行为上一行第i-1个加上第i个            }            pre = temp;//记录上一行            n++;        }        return temp;    }};
0 0