Torna alle sfide
Facile 0 risolte 0% di accettazione

Pascal’s Triangle

Build rows by adding neighboring entries from the previous row.

Cosa imparerai

  • Build each row from the previous one
  • Work with lists of lists
  • Connect rows to binomial coefficients

Problema

Mostra traduzione

The first row is [1]. Each later row starts and ends with 1. Every interior entry is the sum of the two entries immediately above it. Return the first rows rows, beginning with the single 1.

Implement pascals_triangle(rows).

Input

rows: How many rows to generate.

Output

Return a list of rows, starting at the top; each row is a list of integers.

Vincoli

0 ≤ rows ≤ 60. Every entry fits a signed 64-bit integer. Zero rows returns an empty list.

Esempi

Esempio 1
Input:
rows = 4

Output atteso:
expected = [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1]
]
Input:
long long rows = 4;

Output atteso:
std::vector<std::vector<long long>> expected = {
    {1},
    {1, 1},
    {1, 2, 1},
    {1, 3, 3, 1}
};
Input:
long rows = 4;

Output atteso:
long[][] expected = new long[][] {
    new long[] {1},
    new long[] {1, 1},
    new long[] {1, 2, 1},
    new long[] {1, 3, 3, 1}
};

Spiegazione

The 2 in row 3 is 1 + 1. The two interior 3s in row 4 are 1 + 2 and 2 + 1.

Esempio 2
Input:
rows = 0

Output atteso:
expected = []
Input:
long long rows = 0;

Output atteso:
std::vector<std::vector<long long>> expected = {};
Input:
long rows = 0;

Output atteso:
long[][] expected = new long[][] {};

Spiegazione

No rows are requested, so return an empty list.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Each row starts and ends with 1, and interior values come from the two values above them.

Suggerimento 2

Build rows one at a time from the previous row rather than recomputing from scratch.

Suggerimento 3

Handle the zero-row case by returning an empty list immediately.

Complessità attesa

O(rows^2) time, O(rows^2) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.