What I have so far
let threeSum = (array, targetSum) => {
let newArray = []
if (array.length === 0) {
return newArray
}
for (let i = 0; i < array.length; i++) {
const num1 = array[i];
for (let j = i + 1; j < array.length; j++) {
const num2 = array[j];
for (let k = j + 1; k < array.length; k++) {
const num3 = array[k];
if (num1 + num2 + num3 === targetSum) {
newArray.push([num1, num2, num3])
}
}
}
}
return newArray
}
console.log(threeSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
// [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]
This works but only because I'm iterating through the array, I've tried checking the last and first number then slicing the array everytime I recall the function. I've written a base case so far but I'm lost on the recursion step.
This is what I have for the recursion:
let threeSum = (array, targetSum) => {
let newArray = []
if (array.length === 0) {
return newArray
}
let num1 = array[0]
let num2 = array[1]
let num3 = array[2]
if (num1 + num2 + num3 === targetSum) {
newArray.push([num1, num2, num3])
}
return array.slice(1), targetSum
}
console.log(threeSum([12, 3, 1, 2, -6, 5, -8, 6], 0))
// [[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]