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;
	}
}
相关推荐
特立独行的猫A23 分钟前
我给女儿写了个打字练习:一边敲键盘,一边把小学英语单词记牢
java·后端·python
憧憬成为java架构高手的小白2 小时前
LangGraph4j 实战(下)
java
天诰2 小时前
SA-K-11 检索会消失吗与四个未解问题
java·服务器·人工智能·python·机器学习·ai编程
这个昵称不容易6 小时前
SpringBoot「衣依」服装销售平台:144个Java文件180个接口,从挑衣服到收货评价整条链路都在
java·springboot·毕设
计算机毕设定制辅导-无忧学长6 小时前
《基于微信小程序的居家医疗陪护预约系统设计与实现》
java·spring boot·微信小程序·uniapp·居家医疗陪护预约系统
likexuec7 小时前
数据结构(2)
数据结构
文丑颜不良啊8 小时前
LeetCode2221~2240题目解析
java·leetcode
秋饼8 小时前
Computer Use Agent Java 落地实战:感知-行动循环、执行器与安全围栏生产级实现
java·ai·技术分享·后端开发
Navigator_Z8 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack8 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector