[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时候的情况。
分类:
算法题目
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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)