Pascal's Triangle II
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?
Solution
public class Solution {
public List<Integer> getRow(int num) {
int numRows = num + 1;
if (numRows < 1) return new ArrayList<>();
List<Integer> cur = new ArrayList<>();
cur.add(1);
List<Integer> cur1 = new ArrayList<>();
cur1.add(1);
cur1.add(1);
List<List<Integer>> result = new ArrayList<>();
result.add(cur);
result.add(cur1);
if (numRows == 1) {
return cur;
} else if (numRows == 2) {
return cur1;
} else {
for (int i = 3; i <= numRows; i ++) {
List<Integer> prev = result.get(i-2);
List<Integer> newResult = new ArrayList<>();
newResult.add(1);
for(int j = 1; j < i -1; j ++) {
newResult.add(prev.get(j-1) + prev.get(j));
}
newResult.add(1);
result.add(newResult);
}
}
return result.get(result.size()-1);
}
}