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

416 Partition Equal Subset Sum

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

const partitionEqualSubsetSum = nums => {
  let sum = 0
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i]
  }
  if (sum % 2 != 0) {
    return false
  }
  let dp = new Map()
  const dfs = (index, currSum) => {
    const pos = index + '->' + currSum
    if (index == nums.length) {
      if (currSum == sum / 2) {
        return true
      }
      return false
    }
    if (dp.has(pos)) {
      return dp.get(pos)
    }
    let exclude = false,
      include = false
    if (nums[index] + currSum <= sum / 2) {
      include = dfs(index + 1, currSum + nums[index])
    }
    exclude = dfs(index + 1, currSum)
    const result = exclude || include
    dp.set(pos, result)
    return result
  }
  return dfs(0, 0)
}

console.log(partitionEqualSubsetSum([1, 2, 3, 4, 5, 6, 7]))

Created 2022-03-26T19:14:52+00:00 · Edit