我们需要编写一个将整数数组作为唯一参数的JavaScript函数。
该函数应确定是否存在将数组拆分为两个子数组的任何方式,以使两个子数组中存在的元素之和相等。在将元素划分为子数组时,我们必须确保不保留原始数组中的任何元素。
例如-
如果输入数组是-
const arr = [5, 3, 7, 4, 1, 8, 2, 6];
那么输出应该是-
const output = true;
因为所需的子数组是:[5、3、4、6]和[7、1、8、2],它们的总和等于18。
以下是代码-
const arr = [5, 3, 7, 4, 1, 8, 2, 6]; const canPartition = (arr = []) => { const sum = arr.reduce((acc, val) => acc + val); if (sum % 2 !== 0){ return false; }; const target = sum / 2; const array = new Array(target + 1).fill(false); array[0] = true; for (const num of arr) { if (array[target - num]){ return true }; for (let i = target; i >= num; i--) { array[i] = array[i - num]; } } return false; }; console.log(canPartition(arr));输出结果
以下是控制台输出-
true