题目:
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] ]
解答:
帕斯卡三角规律:从1开始,从1结束,下一行中间值等于上一行前2个值之和
代码:
import java.util.*;
public class Solution {
public List<List<Integer>> generate(int numRows) {
Vector<List<Integer>> ret = new Vector<List<Integer>>();
for(int i=0;i<numRows;i++){
Vector<Integer> curRow = new Vector<Integer>();
List<Integer> lastRow = null;
if(i > 0){
lastRow = ret.get(i-1);
}
for(int j=0;j<i+1;j++){
if(j == 0 || j == i)
curRow.add(1);
else{
curRow.add(lastRow.get(j-1) + lastRow.get(j));
}
}
ret.add(curRow);
}
return ret;
}
}