当前位置:网站首页>【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
略
边栏推荐
猜你喜欢

Build finished with errors/Executable Not Found

The future of the hybrid interface: conversational UI

csdn文件导出为pdf

Web系统常见安全漏洞介绍及解决方案-sql注入

Module eight

Browser usage ratio js radar chart

项目管理工具之燃尽图:动态考核团队工作能力

Redis Sentinel原理

Open Kylin openKylin automation developer platform officially released

NowCoderTOP17-22 Binary search/sort - continuous update ing
随机推荐
Are postgresql range queries faster than index queries?
postgresql 范围查询比索引查询快吗?
js right dot single page scrolling introduction page
ARC在编译和运行做了什么?
postgresql generate random date, random time
Simple understanding of GCD
Burndown chart of project management tools: Dynamic assessment of team work ability
比较并交换 (CAS) 原理
Mybaits Frequently Asked Questions Explained
【LeetCode】Day108-和为 K 的子数组
csdn file export to pdf
Build finished with errors/Executable Not Found
通过栗子来学习MySQL高级知识点(学习,复习,面试都可)
nodeJs--querystring模块
NowCoderTOP23-27 Binary tree traversal - continuous update ing
来n遍剑指--05. 替换空格
SQLite3交叉编译
loadrunner录制问题
Mysql+Navicat for Mysql
Kotlin—基本语法 (四)