LeetCode OJ:Pascal's Triangle(帕斯卡三角)

 2023-09-05 阅读 40 评论 0

摘要:GivennumRows, generate the firstnumRowsof Pascal's triangle. For example, givennumRows= 5,Return [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1] ] 帕斯卡三角,很简单的问题,见代码: 1 class Solution { 2 public: 3 vector<vector<int

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

帕斯卡三角,很简单的问题,见代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> generate(int numRows) {
 4         vector<vector<int>> ret;
 5         vector<int> tmpVec;
 6         ret.clear();
 7         tmpVec.clear();
 8         for(int i = 0; i < numRows; ++i){
 9             if(i == 0){
10                 tmpVec.push_back(1);
11             }else{
12                 for(int j = 0; j <= i; ++j){
13                     if(j == 0) tmpVec.push_back(1);
14                     else if(j == i) tmpVec.push_back(1);
15                     else tmpVec.push_back(ret[i - 1][j - 1] + ret[i - 1][j]);
16                 }
17             }
18             ret.push_back(tmpVec);
19             tmpVec.clear();
20         }
21         return ret;
22     }
23 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4918826.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/1336.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息