2023年6月7日 星期三

6/7 每日一題(巴斯卡三角形)

 Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

 

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

 

Constraints:

  • 1 <= numRows <= 30

class Solution:

    def generate(self, numRows: int) -> List[List[int]]:
        mylist=[]
        for i in range(numRows):
            row=[1]*(i+1)
         #先讓全部元素填充1

            for j in range(1,i):
                row[j]=mylist[i-1][j-1]+mylist[i-1][j]
#j範圍設定[1,i-1] ,所以前面兩階[1,0] [1,1]都會是空 到第三階才會開始[1,2]
#mylist[i-1]表示上一層的list ,[j-1]和[j]表示巴斯卡上一層的左右兩項加放入到目前這層的row[j]
#其中,j會重第1項到i-1項 保持首尾項都是1

            mylist.append(row)
        return mylist


標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁