파이썬

[Leetcode] 118. Pascal's Triangle

람쥐썬더123 2023. 9. 8. 22:50

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

 

Row 의 갯수가 주어지고 이미지에 맞게 인덱스를 채워가게끔 출력하면 되는 문제

 

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        result = []

        for row in range(1,numRows+1):    
            result.append([1 for i in range(row)])

        for depth in range(2, len(result)):
            for idx in range(1, len(result[depth])-1):
                result[depth][idx] = result[depth-1][idx-1] + result[depth-1][idx]


        return result

 

 

- list 내의 index를 row의 수에 맞게 1로 채워준다

- index 0, 1 의 값은 1로 고정되어 있어 2부터 마지막  row까지 계산

- 각 row의 index 0 과 -1또한 1로 고정 시키고 이전 row의 바로 윗 값 두개를 더해주며 변환해준다

 

 

애초에 배열을 만들어 놓는게 아니라 한 층씩 쌓아 갈 수 있으면 좀 더 빠르고 효율적으로 가능할 듯 싶다.