Leetcode Pascal's Triangle II

来源:互联网 发布:用友初始化数据库失败 编辑:程序博客网 时间:2024/05/19 11:17
ven an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].



代码如下:

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



然而上面代码中的pre=temp这个复制操作是十分费时的,要想办法去掉从而提升效率,修改后的代码如下:

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> temp(rowIndex+1,1);        for(int i=1;i<=rowIndex;i++)        {            int pre = temp[0];            for(int j=1;j<i;j++)            {                int exchange = temp[j];                temp[j] += pre;                pre = exchange;                          }        }        return temp;    }};