Count pairs of numbers with specific sum

by Krishna Ananthi

JavaScript

function changeSigns(nums, sum) {
  // your code goes here
  let res = 0
  nums.sort((a, b) => a - b)
  const dfs = (index, total) => {
    if (index === nums.length) {
      if (total === sum) res++
      return
    }

    dfs(index + 1, total + nums[index])
    dfs(index + 1, total - nums[index])
  }
  dfs(0, 0)
  return res
}

// debug your code below
console.log(changeSigns([1, 2, 1], 2))