ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Find Right-Triangle Triples

List all integer right triangles with a specified perimeter.

สิ่งที่คุณจะได้เรียนรู้

  • List all integer right triangles for a perimeter
  • Avoid duplicates by ordering sides
  • Prune the search with bounds

โจทย์

ดูฉบับแปล

Find every triple of positive integers a < b < c for which a² + b² = c² and a + b + c = perimeter. Return each triple as [a, b, c], ordered by increasing a and then b. Do not include permutations of the same sides.

Implement pythagorean_triplets(perimeter).

Input

perimeter: The required sum of all three sides.

Output

Return a list of triples in the specified order.

เงื่อนไข

3 ≤ perimeter ≤ 100,000. Return an empty list if no triangle qualifies.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
perimeter = 30

ผลลัพธ์ที่คาดหวัง:
expected = [
    [5, 12, 13]
]
อินพุต:
long long perimeter = 30;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {
    {5, 12, 13}
};
อินพุต:
long perimeter = 30;

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {
    new long[] {5, 12, 13}
};

คำอธิบาย

5 + 12 + 13 = 30 and 5² + 12² = 13². This is the only qualifying triple.

ตัวอย่างที่ 2
อินพุต:
perimeter = 11

ผลลัพธ์ที่คาดหวัง:
expected = []
อินพุต:
long long perimeter = 11;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::vector<long long>> expected = {};
อินพุต:
long perimeter = 11;

ผลลัพธ์ที่คาดหวัง:
long[][] expected = new long[][] {};

คำอธิบาย

No increasing positive integer right-triangle triple sums to 11.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

A valid triple must satisfy both the Pythagorean equation and the perimeter sum.

คำใบ้ 2

Use the perimeter to limit the search instead of trying every ordering of sides.

คำใบ้ 3

Remember to keep only a < b < c, and skip duplicates from symmetric side choices.

ความซับซ้อนที่คาดหวัง

O(n^2) time, O(1) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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