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?
class Solution {
public List<Integer> getRow(int rowIndex) {
if(rowIndex < 0) return new ArrayList<Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(1);
if(rowIndex == 0){
return res;
}
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i = 0;i < rowIndex;i++){
temp.clear();
temp.add(1);
for(int j = 0;j< res.size()-1;j++){
temp.add(res.get(j)+res.get(j+1));
}
temp.add(1);
res.clear();
res.addAll(temp);
}
return res;
}
}
写了这么长久就知道还得练.....下面是更省空间的。
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if (rowIndex < 0)
return list;
for (int i = 0; i < rowIndex + 1; i++) {
list.add(0, 1);
for (int j = 1; j < list.size() - 1; j++) {
list.set(j, list.get(j) + list.get(j + 1));
}
}
return list;
}