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;
}
};
然而上面代码中的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
-
Pascal's Triangle II - LeetCode
-
119. Pascal‘s Triangle II
-
[LeetCode]118. Pascal's Triangle
-
DHU高级程序设计-leetcode刷题剑指 Offer 57 - II. 和为s的连续正数序列
-
Leetcode No.119 Pascal's Triangle II(c++实现)
-
杨辉三角(pascal's triangle)
-
LeetCode-119. Pascal's Triangle II
-
119. Pascal's Triangle II [杨辉三角形2]
-
119. Pascal's Triangle II