js
/**
* arr 排序后的数据
* n 几个数
* start 开始坐标
* target 总和
*/
function nSum(arr, n, start, target) {
if (arr.length < 2) return arr;
if (n < 2) return;
const result = [];
let len = arr.length;
if (n === 2) {
let left = start;
let right = len - 1;
while (left < right) {
const l = arr[left];
const r = arr[right];
const sum = l + r;
if (sum < target) {
// 去重
while (left < right && arr[left] === l) left++;
} else if (sum > target) {
// 去重
while (left < right && arr[right] === r) right--;
} else {
result.push([l, r]);
// 去重
while (left < right && arr[left] === l) left++;
while (left < right && arr[right] === r) right--;
}
}
} else {
for (let i = start; i < len; ) {
let cur = arr[i];
const child = nSum(arr, n - 1, i + 1, target - cur);
if (child.length) {
for (let ch of child) {
result.push([cur, ...ch]);
}
}
// 去重
while (i < len && arr[i] === cur) {
i++;
}
}
}
return result;
}
使用如下
js
let arr = [1, 2, 3, 4, 5, 6, 2, 6, 7, 8, 7, 3, 53, 123];
function threeSum(arr, target) {
arr.sort((a, b) => a - b);
return nSum(arr, 3, 0, target);
}
console.log(threeSum(arr, 14));
// [[1,5,8],[1,6,7],[2,4,8],[2,5,7],[2,6,6],[3,3,8],[3,4,7],[3,5,6]]