新博文地址:[leetcode]Pascal's Triangle
http://oj.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]
]
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
跟杨辉三角略像啊,我的想法很直接,逐行求解,存储,如果有好的方法,请分享一下
public ArrayList<ArrayList<Integer>> generate(int numRows){
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(numRows <= 0){
return result;
}
int[] array = {1};
for(int i = 1; i < numRows; i++){
result.add(convertToList(array));
array = getNextList(array);
}
result.add(convertToList(array));
return result;
}
private ArrayList<Integer> convertToList(int[] array){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int tem : array){
list.add(tem);
}
return list;
}
private int[] getNextList(int[] array){
int[] result = new int[array.length + 1];
result[0] = 1;
result[array.length] = 1;
for(int i = 0; i <= array.length - 2; i++){
result[i + 1] = array[i] + array[i + 1];
}
return result;
}