您的位置:首页 > 其它

[leetcode.com]算法题目 - Pascal's Triangle

2013-09-12 20:53 369 查看
Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]


class Solution {
public:
vector<vector<int> > generate(int numRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(0 == numRows){
vector<vector<int> > result;
return result;
}

vector<vector<int> > result(numRows);

vector<int> first(1,1);
result[0] = first;
for(int i=1;i<numRows;i++){
result[i] = nextTriangle(result[i-1]);
}

return result;
}

vector<int> nextTriangle(vector<int> a){
int k = a.size();
vector<int> next(k+1);
for(int i=0;i<k+1;i++){
if(0==i){
next[i] = a[i];
continue;
}
if(k==i){
next[i] = a[k-1];
continue;
}
next[i] = a[i-1]+a[i];
}
return next;
}
};


我的答案
思路:创建一个函数,使用上一行的vector去计算下一行的vector,然后反复调用即可。需要尤其注意输入的值为0时候的情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: