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

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         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if(0 == numRows){
 7             vector<vector<int> > result;
 8             return result;
 9         } 
10              
11         vector<vector<int> > result(numRows);
12         
13         vector<int> first(1,1);
14         result[0] = first;
15         for(int i=1;i<numRows;i++){
16             result[i] = nextTriangle(result[i-1]);
17         }
18         
19         return result;    
20     }
21     
22     vector<int> nextTriangle(vector<int> a){
23         int k = a.size();
24         vector<int> next(k+1);
25         for(int i=0;i<k+1;i++){
26             if(0==i){
27                 next[i] = a[i];
28                 continue;
29             }
30             if(k==i){
31                 next[i] = a[k-1];
32                 continue;
33             }
34             next[i] = a[i-1]+a[i];
35         }
36         return next;
37     }
38 };
我的答案
复制代码

思路:创建一个函数,使用上一行的vector去计算下一行的vector,然后反复调用即可。需要尤其注意输入的值为0时候的情况。

posted on   Horstxu  阅读(180)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示