Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
<span style="color:#333333;">public class Solution {
public List<Integer> getRow(int rowIndex)
{
int n=0;
List<Integer> list=new ArrayList<Integer>();
while(n<=rowIndex)
{
for(int i=n-1;i>=0;i--)
{
if(i==0)
{
continue;
}
int a=list.get(i)+list.get(i-1);
list.remove(i);
list.add(i,a);
}
list.add(1);
n++;
}
return list;
}
}</span>
上面的方法直接在list上面修改数值,每次都需要用到get(),remove(),add(),效率并不是很高。结果就是
Your runtime beats 4.95% of javasubmissions.
下面的方法使用了一个辅助数组,我们每次支队数组进行操作,知道最后一次,循环到了需要的那一层,再把数组元素赋给list。这种方法效率大大增加 Your runtime beats 85.42% of javasubmissions.
<span style="color:#333333;">public class Solution {
public List<Integer> getRow(int rowIndex)
{
int n=0;
int[] a=new int[rowIndex+1];
LinkedList<Integer> list=new LinkedList<Integer>();
while(n<=rowIndex)
{
for(int i=n-1;i>=0;i--)
{
if(i==0)
continue;
a[i]=a[i-1]+a[i];
if(rowIndex==n)
list.add(a[i]);
}
a[n]=1;
n++;
}
if(rowIndex>0)
list.addFirst(1);
list.add(1);
return list;
}
}</span>