Given a list of numbers, check if it can be partitioned into two parts such that the sum of elements in both parts is the same.
Consider if there is sublists that is half of the total. Iterate through each element in the list. For each element, explore two possibilities:
If the target_sum reaches 0, it means a sublist with the desired sum has been found. Return true.
def check(ls, target): if target == 0: return True if ls[0] > target: return False return check(ls[1:], target - ls[0]) or check(ls[1:], target) ls = [1, 5, 11, 5] print(False if sum(ls) % 2 != 0 else check(ls, sum(ls) // 2))
function check(list, target) { if (target === 0) { return true; } if (list[0] > target) { return false; } return check(list.slice(1), target - list[0]) || check(list.slice(1), target); } const list = [1, 5, 11, 5]; const sum = list.reduce((c, i) => c + i, 0); console.log((sum % 2 != 0) ? false : check(list, sum / 2));