代码如下:
package com.leetcode.recurse;
import java.util.ArrayList;
import java.util.List;
public class YangHuiTriangle {
List<List<Integer>> fatherList = new ArrayList<List<Integer>>();
public static void main(String[] args) {
List<List<Integer>> list = new YangHuiTriangle().generate(5);
System.out.println(list);
}
/**
*
* @param numRows
* @return 通过给定的非负数,返回杨辉三角形
*/
public List<List<Integer>> generate(int numRows) {
if(numRows==1) {
List<Integer> childList = new ArrayList<Integer>();
childList.add(1);
fatherList.add(childList);
}else if(numRows>1){
fatherList = generate(numRows-1);
List<Integer> childList = new ArrayList<Integer>();
int len = fatherList.size();
int before=0,now=0;
for(int index : fatherList.get(len-1)) {
now = index;
childList.add(before+now);
before = index;
}
childList.add(now);
fatherList.add(childList);
}
return fatherList;
}
}
执行输出结果:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]