Files
JavaScript/Recursive/Partition.js
Vedas Dixit e9e3ea4684 Implemented Partition Problem, Recursive problem (#1582)
* Add Tug of War solution using backtracking

* Updated Documentation in README.md

* Added Tug of war problem link

* Updated Documentation in README.md

* Updated Documentation in README.md

* Refactor tugOfWar: remove unused vars, optimize initialization, and remove redundant checks

* Added Function Export Statment

* Updated Documentation in README.md

* Resolved Code Style --Prettier

* Rename "backtrack" to "recurse"

* Fix test case: The difference needs to be exactly 1.

* Code Modification: subsets should have sizes as close to n/2 as possible

* Updated test-case of TugOfWar

* Changed TugOfWar problem to Partition

* Modified partition problem

* Updated Documentation in README.md

* fixed code style

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
2023-11-15 19:22:57 +05:30

40 lines
1.2 KiB
JavaScript

/**
* @function canPartition
* @description Check whether it is possible to partition the given array into two equal sum subsets using recursion.
* @param {number[]} nums - The input array of numbers.
* @param {number} index - The current index in the array being considered.
* @param {number} target - The target sum for each subset.
* @return {boolean}.
* @see [Partition Problem](https://en.wikipedia.org/wiki/Partition_problem)
*/
const canPartition = (nums, index = 0, target = 0) => {
if (!Array.isArray(nums)) {
throw new TypeError('Invalid Input')
}
const sum = nums.reduce((acc, num) => acc + num, 0)
if (sum % 2 !== 0) {
return false
}
if (target === sum / 2) {
return true
}
if (index >= nums.length || target > sum / 2) {
return false
}
// Include the current number in the first subset and check if a solution is possible.
const withCurrent = canPartition(nums, index + 1, target + nums[index])
// Exclude the current number from the first subset and check if a solution is possible.
const withoutCurrent = canPartition(nums, index + 1, target)
return withCurrent || withoutCurrent
}
export { canPartition }