1. Sort, Then Two Pointers Optimal
Intuition
Sorting does two jobs at once: it puts equal values next to each other, so a repeated triplet can be skipped without a set, and it turns "find two numbers summing to -x" into a two-pointer walk. Fix the smallest element, then close the remaining pair from both ends — a sum that is too small can only be helped by moving the left pointer up, too large by moving the right pointer down.
Algorithm
1. Sort the array.
2. For each index i, skip it if it repeats the previous value — that would repeat a triplet.
3. Walk left and right pointers over the rest, summing with nums[i].
4. Too small: move left up. Too large: move right down. Zero: record it, unless left has moved and repeats the previous value — that is the triplet just recorded.
5. After a zero, recorded or not, move left up once; the next turn moves right if it has to.
Time & Space
Time O(n^2) — a linear two-pointer pass for each of n starting elements, after an O(n log n) sort. Space O(1) beyond the output and the sort, which may use up to O(n) of its own in either language.