118. Pascal’s Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路:给定非负整数numRows,生成Pascal三角形的第一个numRows。在Pascal的三角形中,每个数字是它正上方的两个数字的总和。从图中可以得出首尾数字都为1,中间数字res[i][j] = res[i-1][j-1] + res[i-1][j]
代码如下:
public class PascalTriangle { public static List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < numRows; i++) { List<Integer> temp = new ArrayList<>(); if (i == 0) { temp.add(1); } else { for (int j = 0; j < i + 1; j++) { if (j == 0) { temp.add(1); } else if (j == i) { temp.add(1); } else { temp.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j)); } } } res.add(temp); } return res; } }