Pascal's Triangle II

来源:互联网 发布:readfile java 编辑:程序博客网 时间:2024/05/12 12:01

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?


相比之前, 有所改动

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

用的space为两个vector<int>

ve1和ve2的长度为 k, k+1

O(space) = 2k+1

0 0
原创粉丝点击