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 Solution {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> last = new ArrayList<Integer>();
if(rowIndex<0) {
return last;
}
last.add(1);
for(int i=0;i<rowIndex;i++) {
ArrayList<Integer> cur = new ArrayList<Integer>();
for(int j=0;j<=last.size();j++) {
int a = 0;
if(j-1>=0) {
a = last.get(j-1);
}
int b = 0;
if(j<last.size()) {
b = last.get(j);
}
cur.add(a+b);
}
last = cur;
}
return last;
}
}
=========
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i <= rowIndex; i++) {
list.add(0);
}
list.set(0, 1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = i; j > 0; j--) {
int val = list.get(j) + list.get(j - 1);
list.set(j, val);
}
}
return list;
}
}
没有评论:
发表评论