问题描述:
Given an integer numRows, return the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:
思路:
思路不难。就是先建立一个list,list的每个元素也是一个小list,循环n次,每一次增添一个list(即一行数据)。
关键在于:注意到第一行有1个,第二行有2个,第三行有3个,第n行有n个,我们可以通过行数控制每行个数,且每行第一个为1,最后一个也为1,其余的情况可以用上一行的对应数据相加得出。
代码如下:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> myList = new ArrayList<List<Integer>>();
for (int i=0; i<numRows; i++){
List<Integer> eachList = new ArrayList<Integer>();
for (int j=0; j<=i; j++){
if ((j==0)||(j==i)){
eachList.add(1);
}
else{
eachList.add(myList.get(i-1).get(j-1) + myList.get(i-1).get(j));
}
}
myList.add(eachList);
}
return myList;
}
}
遇到的问题与bug:
把list-of-list 实例化的方法如下:
List<List> myList = new ArrayList<List>();
List是一个Interface,无法实例化,它必须借助ArrayList或者LinkedList实例化