1. 程式人生 > >LeetCode刷題EASY篇計算楊輝三角第k行. Pascal's Triangle II

LeetCode刷題EASY篇計算楊輝三角第k行. Pascal's Triangle II

題目

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.


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?

我的解法

沒有思路,用之前的,會求出每一行,明顯空間不滿足要求。

 

正確解法

其實是動態規劃,也是利用行與行之間的規律,從尾部開始到頭部重寫陣列元素。不容易理解,我把手動繪製的思路寫在下面,方便大家理解:

程式碼如下:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        Integer[] array=new Integer[rowIndex+1];
        Arrays.fill(array, 0);
        array[0]=1;
        for(int i=1;i<=rowIndex;i++){
            //始終是一個數組,倒序更新,第一個元素始終為1,無需更新,所以j>0
            for(int j=i;j>0;j--){
                array[j]=array[j]+array[j-1];
            }  
        }
        return Arrays.asList(array);
        
        
    }
}