119 Pascal's Triangle II

weixin_33816300發表於2018-09-16

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

13050335-0778431f61d5ce7d.gif
示意圖

Example:

Input: 3
Output: [1,3,3,1]

Note:

Note that the row index starts from 0.

解釋下題目:

輸出楊輝三角的某一行,注意行是從0開始的

1. 跟118一樣的解法唄

實際耗時:1ms

public List<Integer> getRow(int rowIndex) {
        List<Integer> list = new ArrayList<>();
        list.add(0, 1);
        for (int i = 0; i < rowIndex; i++) {
            //第一位一定是1
            list.add(0, 1);
            for (int j = 1; j < list.size() - 1; j++) {
                list.set(j, list.get(j) + list.get(j + 1));
            }
        }
        return list;
    }

  思路是真的沒什麼好寫的......

時間複雜度O(n)
空間複雜度O(1)

相關文章