code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

494 Target Sum

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const targetSum = (nums, target) => {
  const dp = {}
  const backtrack = (index, currSum) => {
    const pos = index + '->' + currSum
    if (pos in dp) return dp[pos]
    if (index == nums.length) {
      if (currSum == target) {
        return 1
      } else {
        return 0
      }
    }
    dp[pos] = backtrack(index + 1, currSum + nums[index]) + backtrack(index + 1, currSum - nums[index])
    return dp[pos]
  }
  return backtrack(0, 0)
}

console.log(targetSum([1, 1, 1, 1, 1], 3))

Created 2022-03-23T17:46:05+00:00 · Edit