題目:
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
代碼:
import java.util.ArrayList;
import java.util.List;
/**
* @作者:dhc
* @創建時間:20:32 2018/8/1
* @描述:118.楊輝三角(帕斯卡三角形)
*/
public class OneHundredAndEighteen {
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0;i < numRows;i++){
List<Integer> tem = new ArrayList<Integer>();
for(int j = 0;j <= i;j++){
if(j == 0 || j == i){
tem.add(1);
}else{
tem.add((int)result.get(i-1).get(j) + (int)result.get(i-1).get(j - 1));
}
}
result.add(tem);
tem = new ArrayList<Integer>();
}
return result;
}
public static void main(String[] args) {
List<List<Integer>> re = generate(5);
for (int i = 0; i < re.size(); i++) {
List<Integer> tem = re.get(i);
for (int j = 0; j < tem.size(); j++) {
System.out.print(tem.get(j)+" ");
}
System.out.println();
}
}
}