반응형
leetcode.com/problems/pascals-triangle/
내가 푼 코드
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
result = [[1]]
if numRows >= 2:
result.append([1,1])
if numRows >= 3:
for k in range(3, numRows+1):
temp = [1] * k
for i in range(1, k-2+1):
temp[i] = result[k-2][i-1] + result[k-2][i]
result.append(temp)
return result
솔루션 코드 (코드를 좀 더 일반화)
class Solution:
def generate(self, num_rows):
triangle = []
for row_num in range(num_rows):
# The first and last row elements are always 1.
row = [None for _ in range(row_num+1)]
row[0], row[-1] = 1, 1
# Each triangle element is equal to the sum of the elements
# above-and-to-the-left and above-and-to-the-right.
for j in range(1, len(row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append(row)
return triangle
시간복잡도 : O(N^2)
공간복잡도 : O(N^2)
반응형
'프로그래밍 > 알고리즘 문제' 카테고리의 다른 글
[브루트포스/재귀함수] N개 알파벳 중에 R개를 나열하는 경우 (4) | 2021.04.05 |
---|---|
Leet Code 121. Best Time to Buy and Sell Stock (4) | 2021.04.04 |
[이진트리/DFS] Leet code 104 - Maximum Depth of Binary Tree (2) | 2021.04.03 |
[BFS / 이진트리] LeetCode 101. Symmetric Tree (4) | 2021.03.23 |
[재귀호출] LeetCode 70. Climbing Stairs (2) | 2021.03.20 |
댓글