#118 Pascal's 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>> rs = new ArrayList<List<Integer>>();
if (numRows <= 0) return rs;
ArrayList<Integer> elem = new ArrayList<Integer>();
elem.add(1);
rs.add(elem);
for(int i = 1; i < numRows; i++) {
ArrayList elem2 = new ArrayList();
for(int j = 0; j < i; j++) {
if (j == 0)
elem2.add(1) ;
else
elem2.add(elem.get(j) + elem.get(j-1));
}
elem2.add(1);
rs.add(elem2);
elem = elem2;
}
return rs;
}
}
#119 Pascal's Triangle II
题目:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
题解:
public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> rs = new ArrayList<Integer>();
if(rowIndex < 0 ) return rs;
rs.add(1);
for(int i = 1; i <= rowIndex; i++){
ArrayList<Integer> tmp = new ArrayList<Integer>();//若声明在循环体外,则循环时要有tmp.clear()
tmp.add(1);
for(int j = 1; j < i; j++){
tmp.add(rs.get(j-1) + rs.get(j));
}
tmp.add(1);
rs = tmp;
}
return rs;
}
}
写在最后:
List<List<Integer>> ret = new ArrayList<ArrayList<Integer>>();//ArrayList<ArrayList<Integer>> cannot be converted to List<List<Integer>>
List<List<Integer>> ret = new ArrayList<List<Integer>>();//Accepted
本文提供了一种使用Java实现的帕斯卡三角形及其指定行的生成方法。包括两个问题:一是生成指定行数的完整帕斯卡三角形;二是获取帕斯卡三角形中的特定一行。
124

被折叠的 条评论
为什么被折叠?



