問題
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.
例
入力:
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.
入力:
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 つずつ開いてみましょう。
ヒント 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用に調整されています。上記の説明と制約に従ってください。