โจทย์
Build a number triangle: row i (counting from 1) lists the numbers 1, 2, …, i.
Implement number_triangle(rows).
Input
rows: The number of rows.
Output
Return the triangle as a list of rows.
เงื่อนไข
0 ≤ rows ≤ 30
ตัวอย่าง
อินพุต:
rows = 3
ผลลัพธ์ที่คาดหวัง:
expected = [
[1],
[1, 2],
[1, 2, 3]
]
อินพุต:
long long rows = 3;
ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
{1},
{1, 2},
{1, 2, 3}
};
อินพุต:
long rows = 3;
ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
new long[] {1},
new long[] {1, 2},
new long[] {1, 2, 3}
};
คำอธิบาย
Rows are [1], [1, 2] and [1, 2, 3].
อินพุต:
rows = 0
ผลลัพธ์ที่คาดหวัง:
expected = []
อินพุต:
long long rows = 0;
ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {};
อินพุต:
long rows = 0;
ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {};
คำอธิบาย
No rows were requested, so the triangle is empty.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Row i should contain the numbers from 1 up to i in order.
คำใบ้ 2
Grow each row by one element as you move downward.
คำใบ้ 3
When there are no rows, the result should simply be empty.
ความซับซ้อนที่คาดหวัง
O(rows^2) time, O(rows^2) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน