LintCode-Logo
Home
Algorithms
AI
CATnew
VIP
Language
avatarroufoo
Back
1354. Pascal’s Triangle II
Description
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
1.Note that the row index starts from 0.
2.In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Have you met this question in a real interview?
Example
Example:
Input: 3
Output: [1,3,3,1]
Challenge
Could you optimize your algorithm to use only O(k) extra space?
Related Problems
Amazon
3 - Hard
67%
DifficultyEasy
Total Accepted518
Total Submitted810
Accepted Rate63%
Show Tags
Company
Leaderboard - C++
afrozan
7ms
OrionPax
7ms
emmaz
8ms
ziken.neo
8ms
chong58
50ms
Note
迭代计算每行的值,由于更新的过程中会覆盖掉一些后续还要使用的元素,所以用tmp0和tmp1来保存下一次需要相加的两个值。
victoryong
Created at 4 days ago
对任意的n>0有 f(1, n)=1,(n>0) f(n, n)=1,(n>2) f(i,j) = f(i-1, j-1)+f(i, j-1),i>2,j>2, 求第k行。 list用法,set, add
sun533
Created at 7 months ago
Discuss
No topic
- Pascal’s Triangle II
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Example
Example:
Input: 3
Output: [1,3,3,1]
Challenge
Could you optimize your algorithm to use only O(k) extra space?
Notice
1.Note that the row index starts from 0.
2.In Pascal’s triangle, each number is the sum of the two numbers directly above it.
代码如下:
class Solution {
public:
/**
* @param rowIndex: a non-negative index
* @return: the kth index row of the Pascal's triangle
*/
vector<int> getRow(int rowIndex) {
vector<int> result;
if (rowIndex == 0) {
result = {1};
return result;
}
if (rowIndex == 1) {
result = {1,1};
return result;
}
vector<int> formerResult = {1, 1};
result.push_back(1);
for (int i = 2; i < rowIndex + 1; ++i) {
int len = formerResult.size() - 1;
for (int j = 0; j < len; ++j) {
result.push_back(formerResult[j] + formerResult[j + 1]);
}
result.push_back(1);
formerResult = result;
if (i < rowIndex) result = {1};
}
return result;
}
};