美文网首页
119 Pascals Triangle II

119 Pascals Triangle II

作者: yangminz | 来源:发表于2018-07-28 11:16 被阅读5次

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

  • 0
  • huge number 30

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;
    }
}

相关文章

网友评论

      本文标题:119 Pascals Triangle II

      本文链接:https://www.haomeiwen.com/subject/hmqomftx.html