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?
Subscribe to see which companies asked this question
解题思路:用两个ArrayList,一个用于存储上一层,一个用于存储下一层。
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if(rowIndex <= 0)
{
list.add(1);
return list;
}
for(int i = 1; i <= rowIndex; i++)
{
ArrayList<Integer> tmp = new ArrayList<Integer>(list);
list.clear();
list.add(1);
for(int j = 1; j < i; j++)
{
list.add(tmp.get(j-1)+tmp.get(j));
}
list.add(1);
}
return list;
}
}