您的位置:首页 > 编程语言 > Go语言

[LeetCode] Pascal's Triangle II

2013-10-28 09:55 459 查看
Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,

Return
[1,3,3,1]
.

问题描述:给定一个索引值k,返回Pascal's triangle(就是杨辉三角)的第k行。

注意,这里第一行的索引值是0。

Pascal's triangle的第n行的值只和第n-1行的值有关,因此可以用两个容器对上一行和要求的行进行中转。

class Solution {
public:
vector<int> getRow(int rowIndex) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> ivec;
vector<int> ivec2;

if(rowIndex == 0)
return vector<int>(1, 1);
int i = 0, j = 0;
ivec.push_back(1);
for(i = 1; i <= rowIndex; i++) {
for(j = 0; j <= ivec.size(); j++) {
if(j == 0 || j == ivec.size()) {
ivec2.push_back(1);
}
else {
ivec2.push_back(ivec[j-1]+ivec[j]);
}
}
ivec = ivec2;
ivec2.clear();
}
return ivec;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm