Notice
Recent Posts
Recent Comments
Link
오늘도 개발
20. Pascal's Triangle 본문
문제
정수 numRows를 인수로 받아 파스칼의 삼각형을 구하고 반환하라.
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
내가 생각한 해결 방식
def generate(numRows):
i = 0
result = []
while i < numRows:
if i == 0:
result.append([1])
i += 1
else:
# current의 맨 앞에 1 추가
current = [1]
# 직전 배열을 기준으로 삼음
prev = result[i - 1]
for j in range(len(prev)):
if j + 1 < len(prev):
# 현재 요소와 다음 요소를 더한 값을 current에 추가
current.append(prev[j] + prev[j + 1])
# current의 맨 뒤에 1 추가
current.append(1)
result.append(current)
i += 1
return result
다른 해결 방식
Leetcode 유저 ASHOK_KUMAR_MEGHVANSHI/
방식은 같은데 코드가 더 간결함
def generate(numRows):
result = [[1],[1,1]]
for i in range(2,numRows):
new_row = [1]
last_row = result[-1]
for j in range(len(last_row) - 1):
new_row.append(last_row[j] + last_row[j+1])
new_row.append(1)
result.append(new_row)
# numRows가 1인 경우 result만 반환하면 [[1],[1,1]]이 되므로 슬라이싱 필요
return result[:numRows]'자료구조 & 알고리즘 > Leetcode' 카테고리의 다른 글
| 22. Find the Index of the First Occurrence in a String (0) | 2022.10.12 |
|---|---|
| 21. Add Binary (0) | 2022.10.11 |
| 19. Spiral Matrix (1) | 2022.09.22 |
| 17. Plus One (0) | 2022.09.16 |
| 16. Largest Number At Least Twice of Others (0) | 2022.09.14 |