[Leetcode] 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]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
因为需要O(k)的空间,因此需要对同一个数组进行重写,可以从后往前进行覆盖,则没有问题
需要注意的一个问题是 Arrays.asList()操作的不能使基本类型数组
1 public class Solution { 2 public List<Integer> getRow(int rowIndex) { 3 Integer [] row = new Integer[rowIndex+1]; 4 row[0]=1; 5 if(rowIndex==0)return Arrays.asList(row); 6 row[1]=1; 7 if(rowIndex==1) return Arrays.asList(row); 8 for(int i = 2; i<=rowIndex;i++){ 9 row[i]=1; 10 for(int j=i-1;j>=1;j--){ 11 row[j]=row[j]+row[j-1]; 12 } 13 } 14 return Arrays.asList(row); 15 } 16 }