118. 杨辉三角
- 杨辉三角
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
package 每日一题;
import java.util.ArrayList;
import java.util.List;
/*
* 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
*/
public class a118杨辉三角 {
public static void main(String[] args) {
List<List<Integer>> F =generate(10);
for (List<Integer> list : F) {
System.out.println(list);
}
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; i++) { //多少层数
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= i; j++) {//一层有多少个数
if (j == 0 || j == i) {//边界
row.add(1);
} else { //上一层左右两个数相加
row.add(ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j));//重点
}
}
ret.add(row);
}
return ret;
}
}