import java.util.ArrayList;
/**
* 給出一個索引k,返回楊輝三角的第k行
* 例如,k=3,
* 返回[1,3,3,1].
* 備註:
* 你能將你的算法優化到只使用O(k)的額外空間嗎?
*
* 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 Main54 {
public static void main(String[] args) {
System.out.println(Main54.getRow(3));
}
public static ArrayList<Integer> getRow(int rowIndex) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
ArrayList<Integer> array = new ArrayList<>();
if (rowIndex == 0) {
return array;
}
for (int i=0;i<rowIndex;i++) {
ArrayList<Integer> newArray = new ArrayList<>();
if (i > 1) {
array = list.get(i-1);
}
for (int j=0;j<=i;j++) {
if (j==0 || i==j) {
newArray.add(1);
}else{
newArray.add(array.get(j-1)+array.get(j));
}
}
list.add(newArray);
}
return list.get(list.size()-1);
}
}