1. 程式人生 > >LeetCode Pascal's Triangle II

LeetCode Pascal's Triangle II

Problem

Given an index k, return the kth row of the Pascal’s triangle.

For example, given k = 3, Return [1,3,3,1].

Note: Could you optimize your algorithm to use only O(k) extra space?

即直接返回楊輝三角形的某一行元素,額外要求是隻讓使用O(k)的空間

Python 實現


'''
Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?
'''
# author li.hzh class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ result = [1] for i in range(rowIndex): for index in range(len(result)): before = index - 1 if before
< 0: continue elif index == 1: result[index] = result[index] + result[before] else: ori_val = 1 for i in range(1, index): ori_val = result[i] - ori_val result
[index] += ori_val result.append(1) return result print(Solution().getRow(0)) print(Solution().getRow(1)) print(Solution().getRow(2)) print(Solution().getRow(3)) print(Solution().getRow(4))

分析

這裡只給出了我耿直的解法的程式碼。思路很直接,在空間限定的情況下,反推計算每行原始元素的值。然後求得新值,值的結果都儲存在同一個陣列中。

不過值得一提的是,在閱讀別人的答案的過程中,學到了兩個知識點。

一個是Python的map和lambda函式,其實跟Java8裡的完全類似,用這個可以很方便的解答該問題,不過不知道空間控制如何。

另一個就是遞迴,其實這個是應該想到的思路,因為本次計算結果恰好依賴上次的結果。可能由於上一個問題的思維慣性,沒有如此去想,還需要提高。