119 Pascals Triangle II


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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 鮮活的一天,從起床的那刻開始!<感謝電影《我不是藥神》及相關(guān)圖片素材,僅用于個人筆記> 引子 自己的娛樂活動是比較...
    Andrew_LYU閱讀 208評論 0 0
  • 在學(xué)習(xí)golang語言,文檔看的實在是乏味,就想著把常用的算法做個實現(xiàn),邊寫變學(xué)習(xí),想來效果還是不錯的! 1. 堆...
    Diogoxiang閱讀 543評論 0 1
  • 生活,不是假裝,是切實的人生。無論你思考著活,還是任性的存在,生活總是與你千絲萬縷的聯(lián)系著。 現(xiàn)當(dāng)今的城市社會,鮮...
    雲(yún)漠閱讀 510評論 2 3