服务器之家

服务器之家 > 正文

基于Java实现杨辉三角 LeetCode Pascal's Triangle

时间:2020-03-21 12:12     来源/作者:MRR

 Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,

Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

这道题比较简单, 杨辉三角, 可以用这一列的元素等于它头顶两元素的和来求.

数学扎实的人会看出, 其实每一列都是数学里的排列组合, 第4行, 可以用 C30 = 0 C31=3 C32=3 C33=3 来求

基于Java实现杨辉三角 LeetCode Pascal's Triangle

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.ArrayList;
import java.util.List;
public class Par {
public static void main(String[] args) {
System.out.println(generate(1));
System.out.println(generate(0));
System.out.println(generate(2));
System.out.println(generate(3));
System.out.println(generate(4));
System.out.println(generate(5));
 
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>(numRows);
for (int i = 0; i < numRows; i++) {
List<Integer> thisRow = new ArrayList<Integer>(i);
thisRow.add(1);
int temp = 1;
int row = i;
for (int j = 1; j <= i; j++) {
temp = temp * row-- / j ;
thisRow.add(temp);
}
result.add(thisRow);
}
return result;
}
}

以上内容给大家介绍了基于Java实现杨辉三角 LeetCode Pascal's Triangle的相关知识,希望大家喜欢。

标签:

相关文章

热门资讯

玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
超A是什么意思 你好a表达的是什么
超A是什么意思 你好a表达的是什么 2019-06-06
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情 2019-06-22
返回顶部