/**
* 给出一个索引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?
*/
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); } }