描述

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]

]

分析

其实就是杨辉三角,以前用队列写过。

为了和numRows相匹配,以变量i代表当前的行数,那么i-1才是当前行的下标。以j代表当前行的第i个元素(这个j是从下标1开始的)。

代码如下:

class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<int>ele; //store elements of current line
vector<vector<int>>ret; //store all the lines and as a return variable
if(numRows == 0)return ret; //return an empty vector if numRows == 0
int j = 0; //initialize j
for(int i = 1; i <= numRows; ++i){ //note: i begins from 1,means the first line
ele.push_back(1); //push 1 before do any operators in a line
if(i >= 2){
j = 2;
while(j < i){
//because i starts with 1,so i - 1 is current line,while i - 2 is the line before current
//so as to j
ele.push_back(ret[i - 2][j - 2] + ret[i - 2][j - 1]);
++j;
}
ele.push_back(1); //the last number in a line is also 1
}
ret.push_back(ele);
ele.clear(); //each time we finish a line,clear this vector
}
return ret;
}
};

最新文章

  1. form提交的几种方法
  2. cordova常用资料源
  3. html5 上传头像的裁剪
  4. Django--models一对多
  5. BZOJ-1066 蜥蜴 最大流+拆点+超级源超级汇
  6. 在HTML5规范中div中读取预存的data-[key]值
  7. 在Linux中搭建一个FTP服务器
  8. 【转】如何使用KeyChain保存和获取UDID
  9. ios 存储学习笔记
  10. 用C语言实现ipv4地址字符串是否合法
  11. BZOJ3451: Tyvj1953 Normal
  12. CSS3鼠标移入移出图片生成随机动画
  13. 简单dp --- HDU1248寒冰王座
  14. .Net 生成条形码
  15. SQL SERVER:CASE判断空,错误一例
  16. AWS Organizations
  17. C程序第二次作业
  18. iOS开发基础-九宫格坐标(2)之模型
  19. 小tips:JS操作数组的slice()与splice()方法
  20. PythonStudy——名称空间 Name space

热门文章

  1. linux主机内存告警shell脚本
  2. 音视频入门-10-使用libyuv对YUV数据进行缩放、旋转、镜像、裁剪、混合
  3. C#笔试题目总结
  4. [JZOJ5280]膜法师题解--思维+前缀和
  5. VBA循环(十一)
  6. HTML中的图片标签的用法!
  7. 微信小程序 之wxml保留小数点后两位数的方法及转化为字符串的方法
  8. python词云图之WordCloud
  9. 基于numpy实现矩阵计算器
  10. 赤池信息准则AIC,BIC