leetcode118-Pascal‘s Triangle

题目

给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

示例 1:

输入: numRows = 5

输出: \[1,1,1,1,2,1,1,3,3,1,1,4,6,4,1]

分析

充分利用杨辉三角的特性,俩边都是1,中间元素等于上一行当前列元素+上一行当前列元素的前一个元素和

java 复制代码
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

public class pascaTriangle {
	public static void main(String[] args) {
		List<List<Integer>> res = getTrain(5);
		for(List<Integer> lin : res) {
			for(Integer data:lin) {
				System.out.print(data + " ");
			}
			System.out.println();
		}
	}
	public static  List<List<Integer>> getTrain(int n) {
		Integer[][] dp = new Integer[n][0];
		for(int i = 0;i<n;i++) {
			dp[i] = new Integer[i+1];
			Arrays.fill(dp[i],1);
			for(int j  =1;j<i;j++) {
				dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
			}
		}
		List<List<Integer>> res = new ArrayList();
		for(int i = 0;i<n;i++) {
			res.add(Arrays.asList(dp[i]));
		}
		return res;
	}
}
相关推荐
泡海椒12 分钟前
告别 iText 繁杂配置:jquick-pdf 极简 PDF 生成实战(零基础上手)
java·开发语言·pdf
Bs_MoneyMagnet3 小时前
基于springboot+vue的滑雪场票务与装备租赁系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计
AlienZHOU8 小时前
AI Coding 时代下,我的技术面试实践分享
前端·后端·面试
野生技术架构师9 小时前
2026 Java 面试全套总结,八股 + 场景 + AI 相关面试考点
java·人工智能·面试
香吧香9 小时前
java服务异常日志只打印异常类型,没有堆栈定位分析
java·jvm·异常
qq_25183645710 小时前
AI 疾病自查功能SpringbootAI项目实战 · 技术实现文档
java·ai·ai编程
mmmmath_310 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z10 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
逆境不可逃10 小时前
Pi Agent 学习笔记:对话太长以后,如何压缩上下文
java
MetaLite10 小时前
JDK 8~26 核心特性一览:从 Stream 到 Scoped Values
java