| 1 | fun tripletSum(nums: List<Int>): List<List<Int>> { |
| 2 | val triplets = mutableListOf<List<Int>>() |
| 3 | val sortedNums = nums.sorted() |
| 4 | for (i in sortedNums.indices) { |
| 5 | // Optimization: triplets consisting of only positive numbers |
| 6 | // will never sum to 0. |
| 7 | if (sortedNums[i] > 0) { |
| 8 | break |
| 9 | } |
| 10 | // To avoid duplicate triplets, skip 'a' if it's the same as |
| 11 | // the previous number. |
| 12 | if (i > 0 && sortedNums[i] == sortedNums[i - 1]) { |
| 13 | continue |
| 14 | } |
| 15 | // Find all pairs that sum to a target of '-a' (-nums[i]). |
| 16 | var listOfPair = pairSumSortedAllPairs(sortedNums, i + 1, -1 * sortedNums[i]) |
| 17 | for (l in listOfPair) { |
| 18 | triplets.add(listOf(sortedNums[i], l[0], l[1])) |
| 19 | } |
| 20 | } |
| 21 | return triplets |
| 22 | } |
| 23 | |
| 24 | fun pairSumSortedAllPairs(nums: List<Int>, start: Int, target: Int): List<List<Int>> { |
| 25 | val listOfPair = mutableListOf<List<Int>>() |
nothing calls this directly
no test coverage detected