본문 바로가기
Leetcode

[LeetCode] Pascal's Triangle 파이썬 (+Pascal's Triangle II)

by YGSEO 2021. 4. 1.
728x90
class Solution:
    # @return a list of lists of integers
    def generate(self, numRows):
        result = []
        for i in range(numRows):
            result.append([])
            for j in range(i + 1):
                if j in (0, i): # i==j(far right) or (j,0) (far left)
                    result[i].append(1)
                else:
                    result[i].append(result[i - 1][j - 1] + result[i - 1][j]) # left-leftup + left-up
        return result

array 채우기

for j in range(i+1): fill row element

 


Pascal's Triangle II

다른건 i range를 +1 해주고 return시 rowIndex로

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        result = []
        for i in range(rowIndex+1):
            result.append([])
        # print(result)
            for j in range(i + 1):
                if j in (0, i):
                    result[i].append(1)
                else:
                    result[i].append(result[i - 1][j - 1] + result[i - 1][j])
        return result[rowIndex]

 

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/pascals-triangle.py

 

 

 

728x90

댓글