본문 바로가기
Computer/Algorithm

LeetCode - Pascal's Triangle

by HanDongWook 2022. 10. 1.
반응형
8000266Add to ListShare

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

 

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Constraints:

  • 1 <= numRows <= 30

풀이(Kotlin):

fun generate(numRows: Int): List<List<Int>> {
    val ans = mutableListOf<List<Int>>(listOf(1))
    if (numRows == 1) return ans
    ans.add(listOf(1, 1))
    if (numRows == 2) return ans
    for (i in 2 until  numRows) {
        val before = ans[i-1]
        val new = arrayListOf<Int>(1, 1)
        for (j in 0 until before.lastIndex) {
            new.add(j+1, before[j] + before[j+1])
        }
        ans.add(new)
    }
    return  ans
}
반응형

'Computer > Algorithm' 카테고리의 다른 글

백준 1699  (1) 2022.10.05
LeetCode - Plus One  (0) 2022.10.01
LeetCode - Binary Tree Postorder Traversal  (0) 2022.09.30
LeetCode - Binary Tree Preorder Traversal  (0) 2022.09.30
LeetCode - Binary Tree Inorder Traversal  (0) 2022.09.30

댓글