• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

C++实现LeetCode(118.杨辉三角)

c++ 搞代码 4年前 (2022-01-06) 21次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了C++实现LeetCode(118.杨辉三角),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下

[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]
]

杨辉三角是二项式系数的一种写法,如果熟悉杨辉三角的五个性质,那么很好生成,可参见另一篇博文Pascal’s Triangle II。具体生成算是:每一行的首个和结尾一个数字都是1,从第三行开始,中间的每个数字都是上一行的左右两个数字之和。代码如下:

 class Solution { public: vector<vector> generate(int numRows) { vector<vector> res(numRows, vector()); for (int i = 0; i <numRows; ++i) { res[i].resize(i + 1, 1); for (int j = 1; j <i; ++j) { res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; } } return res; } };

类似题目:

Pascal’s Triangle II

参考资料:

https://leetcode.com/problems/pascals-triangle/

https://leetcode.com/problems来源gaodai$ma#com搞$代*码*网/pascals-triangle/discuss/38150/My-C%2B%2B-code-0ms

以上就是C++实现LeetCode(118.杨辉三角)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++实现LeetCode(118.杨辉三角)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址