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,從第三行開始,中間的每個數字都是上一行的左右兩個數字之和
public class l118_pascaltriangle {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> res=new ArrayList<>(numRows);
for(int i=0;i<numRows;i++){
ArrayList<Integer> temp=new ArrayList<>(i);
for(int j=0;j<=i;j++){
if(j==0||j==i)//第一個和最後一個是1
temp.add(1);
else {
temp.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
}
}
res.add(temp);
}
return res;
}
LeetCode(119)-pascal triangle 2
Given an index k, return the k th row of the Pascal’s triangle.
For example, given k = 3,
Return[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
public class l119_pascaltriangle2 {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<ArrayList<Integer>> res=new ArrayList<>();
for(int i=0;i<=rowIndex;i++){
ArrayList<Integer> temp=new ArrayList<>();
for(int j=0;j<=i;j++){
if(j==0||j==i)
temp.add(1);
else
temp.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
}
res.add(temp);
if(i==rowIndex){
return temp;
}
}
return null;
}