[leetcode] problem 119 – pascal’s triangle ii

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.

Note that the row index starts from 0.

EpVNMq.gif

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example

Input: 3

Output: [1,3,3,1]

Follow up

Could you optimize your algorithm to use only O(k) extra space?

Code

1
2
3
4
5
6
7
8
9
10
11
12
public List<Integer> (int rowIndex) {
List<Integer> triangle = new ArrayList<>();

for (int idx = 0; idx <= rowIndex; idx++) {
triangle.add(1);

for (int num = idx - 1; num > 0; num--)
triangle.set(num, triangle.get(num) + triangle.get(num - 1));
}

return triangle;
}