LeetCode in Kotlin

118. Pascal’s Triangle

Easy

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:

Solution

class Solution {
    fun generate(numRows: Int): List<List<Int>> {
        val output: MutableList<List<Int>> = ArrayList()
        for (i in 0 until numRows) {
            val currRow: MutableList<Int> = ArrayList()
            for (j in 0..i) {
                if (j == 0 || j == i || i <= 1) {
                    currRow.add(1)
                } else {
                    val currCell = output[i - 1][j - 1] + output[i - 1][j]
                    currRow.add(currCell)
                }
            }
            output.add(currRow)
        }
        return output
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy