119 Pascals Triangle II

2018-07-28  本文已影响5人  yangminz

title: Pascals Triangle II
tags:
- pascals-triangle-ii
- No.119
- simple
- discrete-mathematics
- overflow


Description

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.

img

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?

Corner Cases

Solutions

Naive

Use the recursive relationship bellow:

\binom{n}{k+1} = \binom{n}{k} \times \frac{n-k}{k+1} \in \mathbb{N}

Use type Long since the integer overflows when n is big.

The time complexity and space complexity are all O(n):

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> lst = new LinkedList<>();
        if (rowIndex == 0) {lst.add(1);return lst;}

        long   cni = 1;
        lst.add((int)cni);
        for (int i=0; i<rowIndex; i++) {
            cni = cni*(rowIndex-i)/(i+1);
            lst.add((int)cni);
        }
        
        return lst;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读