2019년 5월 29일 수요일

[leetcode] 118. Pascal's Triangle

원문)
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

번역)
양수 숫자열이 주어졌을때, 파스칼 삼각형을 처음 열부터 만들어라.


예제)



In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

문제접근)

우선 첫번째는 넣어두고
그 다음부터는 이전 배열저장된것을 가져와서 각각 더해주고 넣어준다.
그리고 양끝에 1을 넣어준다.


코드)



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        answer = []
        
        for i in range(numRows):
            if i == 0:
                answer.append([1])
            else:
                tmp = [1]
                prev = answer[i - 1]
                l = len(prev)
                if l > 1:
                    for i in range(1, l):
                        tmp.append(prev[i-1] + prev[i])
                tmp.append(1)
                answer.append(tmp)
        return answer


댓글 없음:

댓글 쓰기