ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [LeetCode / Kotlin] Pascal's Triangle
    ETC 2024. 7. 11. 20:12
    반응형

    문제

    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

     

    나의 풀이

    1. 부모자식의 관계를 파악한다. 예를들어, (2,1) 의 경우 (1,0) + (1,1) 이다. 
    그러므로,  ans[i][j] = ans[i-1][j-1] + ans[i-1][k] 이다.

     

    2. 1의 공식에서 인덱스를 벗어나는 경우를 처리한다.

    class Solution {
        fun generate(numRows: Int): List<List<Int>> {
            val ans = mutableListOf<List<Int>>().apply {
                this.add(listOf(1))
            }
            
            for (i in 1 until numRows) {
                val li = mutableListOf<Int>()
    
                for (j in 0..i) {
                    if (j >= i) {
                        li.add(1)
                        continue
                    }
    
                    val m = i -1
                    val n = j -1
                    if (n < 0) {
                        li.add(1)
                        continue
                    }
                    li.add(ans[m][n] + ans[m][j])
                }
    
                ans.add(li)
            }
    
            return ans
        }
    }

     

    반응형

    'ETC' 카테고리의 다른 글

    [LeetCode / Kotlin] Merge Intervals  (0) 2024.07.12
    [LeetCode / Kotlin] Add Binary  (0) 2024.07.12
    [LeetCode / Kotlin] Spiral Matrix  (0) 2024.07.11
    [LeetCode / Kotlin] Search Insert Position  (0) 2024.07.11
    [LeetCode / Kotlin] Diagonal Traverse  (0) 2024.07.11
Designed by Tistory.