leetcode easy : Pascal's Triangle
https://leetcode.com/problems/pascals-triangle/
Pascal's Triangle - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
간단한 dp문제다. 원래 easy 잘 안푸는데 같이 스터디하는 분이랑 난이도를 맞추기 위해 easy도 풀기 시작
첫 풀이
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
answer = []
line = [1]
for i in range(numRows):
if i > 0:
newline = [1]
for j in range(i-1):
newline.append(line[j] + line[j+1])
newline.append(1)
line = newline
answer.append(line[:])
return answer
좀 더 짧게
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
answer = [[1]]
line = [1]
for i in range(numRows-1):
line = [1] + [line[x] + line[x+1] for x in range(len(line)-1)] + [1]
answer.append(line[:])
return answer
다른 사람 풀이
def generate(self, numRows):
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]