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] ]生成给定行数的帕斯卡三角形。
利用帕斯卡三角形的性质即可很简单的解决。 性质:第n行的第1个数为1,第二个数为1×(n-1),第三个数为1×(n-1)×(n-2)/2,第四个数为1×(n-1)×(n-2)/2×(n-3)/3…依此类推。
public class leetcode118 { public List<List<Integer>> generate(int numRows) { List<List<Integer>> res = new ArrayList<>(); for (int n = 1; n <= numRows; n++) { List<Integer> temp = new ArrayList<>(); int num = 1; for (int k = 1; k <= n; k++) { if (k == 1) num = 1; else num = num * (n - k+1) / (k - 1); temp.add(num); } res.add(temp); } return res; } }