当前位置:网站首页>通过二维顺序表实现杨辉三角
通过二维顺序表实现杨辉三角
2022-07-29 13:31:00 【陈亦康】
给定一个非负整数
numRows,生成「杨辉三角」的前numRows行。在「杨辉三角」中,每个数是它左上方和右上方的数的和。

通过一个二维顺序表实现:

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<>();
List<Integer> line = new ArrayList<>();
line.add(1);
ret.add(line);//第一行第一列增加1
for(int i = 1; i < numRows; i++){
List<Integer> line2 = new ArrayList<>();
for(int j = 0; j <= i; j++){
if(j == 0 || j == i){ //第一列和每行最后一列打印1
line2.add(1);
}
else{ //其他行求下标为[i-1][j-1]+[i-1][j]的值即可
int num = ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j);
line2.add(num);
}
}
ret.add(line2);//增加到一维的顺序表中
}
return ret;
}
}边栏推荐
猜你喜欢
随机推荐
上线前配置
gdb调试常用概念整理
How to Improve Embedded Programming with MISRA
阿里巴巴 CTO 程立:开源是基础软件的源头!
Create and copy conda environment
如何使用MISRA改进嵌入式编程
连接oracle数据库指令
Legendary version adds npc modification, adds npc method and configuration parameter tutorial
浅谈防勒索病毒方案之主机加固
【论文阅读】Anomaly Detection in Video via Self-Supervised and Multi-Task Learning
PHP代码审计得这样由浅入深地学
企业需要知道的5个 IAM 最佳实践
The core principles of electronic games
力扣 206.反转链表--递归解决
即时通讯移动端开发之网络连接优化
线程池拒绝策略详解
Vscode builds ESP32-C3 development environment
plsql连接oracle使用完毕之后关闭问题
电子游戏的核心原理
The Advanced Guide to the Computer Professional Interview








