Create a function rowSum(num)
that takes a positive integer num
, which represents the row index of Pascal’s Triangle, and returns the sum of the elements in that row. Pascal’s Triangle starts at row 0 with [1]
. The first row is [1, 1]
, the second row is [1, 2, 1]
, and each subsequent row is formed by adding pairs of numbers from the previous row. For example, row 3 would be [1, 3, 3, 1]
, and so on.
Given num
, your goal is to return the sum of the numbers in that row.
For example, if num
is 4, the sum of the row [1, 4, 6, 4, 1]
is 16
.
Examples:
Input: 1
Output: 2Input: 2
Output: 4
// Function to generate the nth row of Pascal's Triangle
public static List generatePascalRow(int num) {
List row = new ArrayList<>();
row.add(1); // First element is always 1
for (int i = 1; i <= num; i++) {
// Calculate each element in the row based on the previous element
int nextElement = (row.get(i - 1) * (num - i + 1)) / i;
row.add(nextElement);
}
return row;
}