题目:
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
思路:下一行数据是上一行两个相邻数相加。
代码:
til.ArrayList; public class Solution { public ArrayList<ArrayList<Integer>> generate(int numRows) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(numRows<=0){ return result; } ArrayList<Integer> pre = new ArrayList<>(); pre.add(1); result.add(pre); for(int i=2;i<=numRows;i++){ ArrayList<Integer> current = new ArrayList<>(); current.add(1); for(int j=0;j<pre.size()-1;j++){ current.add(pre.get(j)+pre.get(j+1)); } current.add(1); result.add(current); pre = current; } return result; } }