leetcode 119. pascal’s triangle ii

119. Pascal’s Triangle II

Difficulty: Easy

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.


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

Example:

1
2
Input: 3
Output: [1,3,3,1]

Follow up:

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

Solution

Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class  {
public List<Integer> getRow(int rowIndex) {
if (rowIndex < 0) {
return new ArrayList<>();
}

int[][] dp = new int[2][rowIndex + 1];
dp[0][0] = 1;
dp[1][0] = 1;
for (int i = 1; i <= rowIndex; i++) {
for (int j = 1; j <= i; j++) {
dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + dp[(i - 1) % 2][j];
}
}
List<Integer> result = new ArrayList<>();
for (int n : dp[rowIndex % 2]) {
result.add(n);
}
return result;
}
}