Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Pascal’s Triangle

Build rows by adding neighboring entries from the previous row.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
rows = 4

Kết quả mong đợi:
expected = [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1]
]
Đầu vào:
long long rows = 4;

Kết quả mong đợi:
std::vector<std::vector<long long>> expected = {
    {1},
    {1, 1},
    {1, 2, 1},
    {1, 3, 3, 1}
};
Đầu vào:
long rows = 4;

Kết quả mong đợi:
long[][] expected = new long[][] {
    new long[] {1},
    new long[] {1, 1},
    new long[] {1, 2, 1},
    new long[] {1, 3, 3, 1}
};

Giải thích

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

Ví dụ 2
Đầu vào:
rows = 0

Kết quả mong đợi:
expected = []
Đầu vào:
long long rows = 0;

Kết quả mong đợi:
std::vector<std::vector<long long>> expected = {};
Đầu vào:
long rows = 0;

Kết quả mong đợi:
long[][] expected = new long[][] {};

Giải thích

No rows are requested, so return an empty list.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.