欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode Pascal's Triangle II

程序员文章站 2024-02-21 12:12:04
...
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;
    }
};

Leetcode Pascal's Triangle II


然而上面代码中的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;
    }
};

Leetcode Pascal's Triangle II