[leetcode] 119. Pascal's Triangle II

来源:互联网 发布:农村淘宝店铺 编辑:程序博客网 时间:2024/06/05 21:50

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(k)的space。其实产生pascal triangle是有规律的。具体实现见code。

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> ret;                for(int i=0;i<rowIndex+1;i++){            for(int j=ret.size()-2; j>=0; j--){                ret[j+1] += ret[j];            }            ret.push_back(1);        }                return ret;            }};





0 0
原创粉丝点击