当前位置:网站首页>【LeetCode】118.杨辉三角
【LeetCode】118.杨辉三角
2022-07-31 10:03:00 【酥酥~】
题目
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
提示:
1 <= numRows <= 30
题解
f(i,0) = f(i,i) = 1
f(i,j) = f(i-1,j-1)+f(i-1,j)
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> result;
for(int i=0;i<numRows;i++)
{
vector<int> tmp(i+1);
tmp[0] = tmp[i] = 1;
for(int j=1;j<i;j++)
{
tmp[j] = result[i-1][j-1]+result[i-1][j];
}
result.push_back(tmp);
}
return result;
}
};
//改良
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> result(numRows);
for(int i=0;i<numRows;i++)
{
result[i].resize(i+1);
result[i][0] = result[i][i] = 1;
for(int j=1;j<i;j++)
{
result[i][j] = result[i-1][j-1]+result[i-1][j];
}
}
return result;
}
};
阶乘法
i,j从0开始编号,则f(i,j) = C(j,i)
例:C(2,4) = 6, C(1,4) = 4
略
边栏推荐
猜你喜欢

js right dot single page scrolling introduction page

Redis Cluster - Sentinel Mode Principle (Sentinel)

Redis集群-哨兵模式原理(Sentinel)

loadrunner脚本--添加集合点

loadrunner-controller-目标场景Schedule配置

细讲DDD领域驱动设计

Are postgresql range queries faster than index queries?

VMware下安装win10启动后进入Boot Manger界面如何解决

Flink1.15 source code reading - PER_JOB vs APPLICATION execution process

Kotlin—基本语法(三)
随机推荐
Implement a thread pool
【职场杂谈】售前工程师岗位的理解杂谈
(C语言)程序环境和预处理
混合型界面:对话式UI的未来
djangoWeb应用框架+MySQL数据4
NowCoderTOP17-22 Binary search/sort - continuous update ing
Chapter Six
乐观锁和悲观锁
自定义v-drag指令(横向拖拽滚动)
Module eight
Build finished with errors/Executable Not Found
Gradle series - Groovy overview, basic use (based on Groovy document 4.0.4) day2-1
NowCoderTOP23-27 Binary tree traversal - continuous update ing
nodeJs--url模块
Kotlin—基本语法(二)
Come n times with the sword--05. Replace spaces
Burndown chart of project management tools: Dynamic assessment of team work ability
Source code analysis of GZIPInputStream class
Flink1.15 source code reading flink-clients - flink command line help command
loadrunner脚本--添加集合点