簡単 0件解決済み 正答率0%

Pascal’s Triangle

Build rows by adding neighboring entries from the previous row.

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

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

例

例 1
入力:
rows = 4

期待される出力:
expected = [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1]
]
入力:
long long rows = 4;

期待される出力:
std::vector<std::vector<long long>> expected = {
    {1},
    {1, 1},
    {1, 2, 1},
    {1, 3, 3, 1}
};
入力:
long rows = 4;

期待される出力:
long[][] expected = new long[][] {
    new long[] {1},
    new long[] {1, 1},
    new long[] {1, 2, 1},
    new long[] {1, 3, 3, 1}
};

解説

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

例 2
入力:
rows = 0

期待される出力:
expected = []
入力:
long long rows = 0;

期待される出力:
std::vector<std::vector<long long>> expected = {};
入力:
long rows = 0;

期待される出力:
long[][] expected = new long[][] {};

解説

No rows are requested, so return an empty list.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。