Problem

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?

Solution

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> res = new ArrayList<>();
        if (rowIndex < 0) return res;
        
        //rowIndex is zero-based, so from 0 to rowIndex
        for (int i = 0; i <= rowIndex; i++) {
            res.add(0, 1);
            for (int j = 1; j < res.size()-1; j++) {
                res.set(j, res.get(j)+res.get(j+1));
            }
        }
        
        return res;
    }
}

linspiration
161 声望53 粉丝