import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * Source : https://oj.leetcode.com/problems/pascals-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] * ] * * */public class PascalTiangle { /** * 生成杨辉三角(帕斯卡三角形) * * @param n * @return */ public List > generate (int n) { List > result = new ArrayList >(n); if (n == 0) { return result; } result.add(Arrays.asList(new Integer[]{1})); for (int i = 2; i <= n; i++) { List list = new ArrayList (i); list.add(1); for (int j = 1; j < i-1; j++) { list.add(result.get(i-2).get(j-1) + result.get(i-2).get(j)); } list.add(1); result.add(list); } return result; } public void print (List > list) { for (int i = 0; i < list.size(); i++) { for (int j = 0; j <= list.size() - i; j++) { System.out.print(" "); } System.out.println(Arrays.toString(list.get(i).toArray(new Integer[list.get(i).size()]))); } } public static void main(String[] args) { PascalTiangle pascalTiangle = new PascalTiangle(); pascalTiangle.print(pascalTiangle.generate(5)); }}