LeetCode – Pascal’s Triangle II (Java)

Given an index k, return the kth row of the Pascal’s triangle. For example, when k = 3, the row is [1,3,3,1].

Analysis

This problem is related to Pascal’s Triangle which gets all rows of Pascal’s triangle. In this problem, only one row is required to return.

Pascal's Triangle II

Java Solution

public List<Integer> getRow(int rowIndex) {
	ArrayList<Integer> result = new ArrayList<Integer>();
 
	if (rowIndex < 0)
		return result;
 
	result.add(1);
	for (int i = 1; i <= rowIndex; i++) {
		for (int j = result.size() - 2; j >= 0; j--) {
			result.set(j + 1, result.get(j) + result.get(j + 1));
		}
		result.add(1);
	}
	return result;
}

3 thoughts on “LeetCode – Pascal’s Triangle II (Java)”

  1. Here you go. One loop. No additional storage. Same time bounds but faster in practice.


    public List getRow(int rowIndex) {
    ArrayList result = new ArrayList();

    long c = 1;
    for (int j = 0; j <= rowIndex; j++) {
    result.add((int) c);
    c *= rowIndex - j;
    c /= j + 1;
    }
    return result;
    }

  2. The nth row of a pascal triangle also represents the coefficient of the expansion of a binomial to the order of n. So one could also compute the nth row of the pascals triangle directly without having to loop to the row index we are interested in..

  3. Thank you for the post! I can not run this code for rowIndex = 2 since result.size() is equal to 1, so we never enter the second loop, right? So, how we calculate the middle element in row 2?

    [since we have only this one in result: result.add(1)so result.size()=1 and then we cannot enter this loop: for (int j = result.size() – 2; j >= 0; j–)right?]

Leave a Comment