LeetCode 118. Pascal’s Triangle

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解析:
根据指定的数值,输出杨辉三角。杨辉三角中每一层的元素是是上一层垂直位置的两个元素之和。
代码如下:
[cc lang=”C++”]
class Solution {
public:
vector> generate(int numRows) {
vector> result;
for(int i = 0; i < numRows; i++) { vector ans(i+1,1);
for(int index = 1; index < i; index ++) { ans[index] = result[i-1][index-1] + result[i-1][index]; } result.push_back(ans); } return result; } }; [/cc] 运行结果:

One Comment

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据