119. Pascal's Triangle II

Description

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

DP

使用O(k)额外空间的话,只需要一个List就可以了,然后注意每行需要从后向前遍历更新值。

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

你可能感兴趣的:(119. Pascal's Triangle II)