leetcode解题报告(23):Pascal's Triangle
2024-08-27 09:27:34
描述
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;
}
};
最新文章
- form提交的几种方法
- cordova常用资料源
- html5 上传头像的裁剪
- Django--models一对多
- BZOJ-1066 蜥蜴 最大流+拆点+超级源超级汇
- 在HTML5规范中div中读取预存的data-[key]值
- 在Linux中搭建一个FTP服务器
- 【转】如何使用KeyChain保存和获取UDID
- ios 存储学习笔记
- 用C语言实现ipv4地址字符串是否合法
- BZOJ3451: Tyvj1953 Normal
- CSS3鼠标移入移出图片生成随机动画
- 简单dp --- HDU1248寒冰王座
- .Net 生成条形码
- SQL SERVER:CASE判断空,错误一例
- AWS Organizations
- C程序第二次作业
- iOS开发基础-九宫格坐标(2)之模型
- 小tips:JS操作数组的slice()与splice()方法
- PythonStudy——名称空间 Name space