119 Pascal Triangle ii
Question:
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?
Code:
public class Solution {
public List<Integer> getRow(int rowIndex) {
ArrayList<Integer> last = new ArrayList<Integer>();
last.add(1);
for (int i = 0; i < rowIndex; i++) {
ArrayList<Integer> row = new ArrayList<Integer>();
for (int j = 0; j < last.size() + 1; j++) {
if (j == 0 || j == last.size()) {
row.add(1);
} else {
row.add(last.get(j-1) + last.get(j));
}
}
last = row;
}
return last;
}
}
updated:
public class Solution {
public List
// since题目从0开始,让循环从0开始,此时,每一行的长度为i+1,最后一个值的index为i。
for (int i = 0; i <= rowIndex; i++) {
List<Integer> list = new ArrayList<Integer>();
// 找最后一个位置上的index应该先找长度,然后找长度和上一重循环的对应关系。
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
list.add(1);
} else {
list.add(last.get(j - 1) + last.get(j));
}
}
last = list;
}
return last;
}
}