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;
	}
}
相关推荐
hweiyu0021 小时前
数据结构:布隆过滤器
数据结构
阿拉斯攀登21 小时前
Spring Boot 深度解析:核心原理与自动配置全解
java·spring boot
AM越.21 小时前
Java设计模式超详解--观察者设计模式
java·开发语言·设计模式
专注VB编程开发20年21 小时前
c#语法和java相差多少
java·开发语言·microsoft·c#
超级大福宝21 小时前
C++ 中 unordered_map 的 at() 和 []
数据结构·c++
有一个好名字21 小时前
设计模式-单例模式
java·单例模式·设计模式
2301_7973122621 小时前
学习Java26天
java·开发语言
cike_y21 小时前
JSP原理详解
java·开发语言·jsp
invicinble21 小时前
关于springboot引入traceid来保障可观测型
java·spring boot·后端
仰泳的熊猫1 天前
1037 Magic Coupon
数据结构·c++·算法·pat考试