2019年9月13日
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
vector
for(int i = 0; i < numRows; i++)
{
vector
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