https://leetcode.com/problems/pascals-triangle-ii/
문제에서 설명하는대로, 파스칼의 삼각형을 구현한 후 rowIndex 에 맞는 리스트를 반환한다.
파스칼의 삼각형을 자세히 보면 중앙을 기준으로 대칭을 이루고 있다.
따라서 파스칼의 삼각형을 구현할 때 리스트의 반만 구현하고
리스트를 뒤집은 리스트를 덧붙여서 반환하면 된다.
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
pascal = []
for n in range(0, rowIndex+1):
if(n==0): pascal.append([1])
else:
l = [1,]
for i in range(0,len(pascal[-1])-1):
a = pascal[-1][i]
b = pascal[-1][i+1]
l.append(a+b)
if(n%2==0): l.append(pascal[-1][-1]*2)
pascal.append(l)
if(rowIndex%2==0): return pascal[rowIndex]+pascal[rowIndex][-2::-1]
else: return pascal[rowIndex]+pascal[rowIndex][::-1]
< English (feedback by ChatGPT) >
As the description, we implement Pascal's Triangle and return a list according to 'rowIndex'.
(As described in the problem, we implement Pascal's Triangle and return the row corresponding to the given rowIndex.)
Each Pascal's Triangle rows have a symmetry.
(Each row in Pascal's Triangle is symmetric around its center.)
So we implement half of rows of Pascal's Triangle and return a list at 'rowIndex' appending to its reversed list.
(So instead of generating the whole row, we can build just the first half and then append its reversed version to complete the row.)
'Coding Interview' 카테고리의 다른 글
[leetcode] 141. Linked List Cycle (0) | 2025.05.09 |
---|---|
[leetcode] 121. Best Time to Buy and Sell Stock (0) | 2025.05.09 |
[leetcode] 112. Path Sum (0) | 2025.05.08 |
[leetcode] 111. Minimum Depth of Binary Tree (0) | 2025.05.07 |
[leetcode] 110. Balanced Binary Tree (0) | 2025.05.06 |