https://leetcode.com/problems/pascals-triangle/
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
代码:
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ls = new ArrayList<List<Integer>>(numRows);
for(int i = 0;i<numRows;i++)
{
List<Integer> ls1 = new ArrayList<Integer>();
for(int j = 0;j<=i;j++)
{
ls1.add(0);
}
ls1.add(0, new Integer(1));
ls1.add(i, new Integer(1));
ls.add(ls1.subList(0, i+1));
for(int j = 1;j<i;j++)
if(i>=1)
{
ls.get(i).set(j, ls.get(i-1).get(j-1)+ls.get(i-1).get(j));
}
}
return ls;
}
}总结:ArrayList<E>类的add(int index,Object o)方法并不是普通的向List中加入元素,而是插入(数组的插入需要后移),意味着当index<size时会抛出异常,这里纠结了好久。该方法的详细说明如下:
add
public void add(int index,
E element)
- 将指定的元素插入此列表中的指定位置。向右移动当前位于该位置的元素(如果有)以及所有后续元素(将其索引加 1)。
-
- 参数:
index- 指定元素所插入位置的索引element- 要插入的元素- 抛出:
IndexOutOfBoundsException- 如果索引超出范围 (index < 0 || index > size())