ง่าย 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก