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;
	}
}
相关推荐
程序员-King.5 小时前
day150—数组—二叉树的锯齿形层序遍历(LeetCode-103)
算法·leetcode·二叉树
sin_hielo5 小时前
leetcode 3314(位运算,lowbit)
数据结构·算法·leetcode
Remember_9935 小时前
【数据结构】深入理解排序算法:从基础原理到高级应用
java·开发语言·数据结构·算法·spring·leetcode·排序算法
bybitq5 小时前
Leetcode-124-二叉树最大路径和-Python
算法·leetcode·深度优先
indexsunny5 小时前
互联网大厂Java求职面试实战:Spring Boot微服务与Kafka消息队列场景解析
java·spring boot·面试·kafka·microservices·interview·distributed systems
qq_12498707535 小时前
基于Spring Boot的心理咨询预约微信小程序(源码+论文+部署+安装)
java·spring boot·后端·spring·微信小程序·小程序·毕业设计
AlenTech5 小时前
1683. 无效的推文 - 力扣(LeetCode)
leetcode
jiayong235 小时前
Tomcat Servlet容器与生命周期管理面试题
java·servlet·tomcat
鱼跃鹰飞5 小时前
Leetcode会员专享题:426.将二叉搜索树转换为排序的双向链表
数据结构·算法·leetcode·链表·深度优先
漫随流水5 小时前
leetcode回溯算法(39.组合总和)
数据结构·算法·leetcode·回溯算法