How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 1059
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  长情又很酷
    2020-12-02 11:58

    First, if the elements are integers, check that the total is evenly divisible by two- if it isn't success isn't possible.

    I would set up the problem as a binary tree, with level 0 deciding which set element 0 goes into, level 1 deciding which set element 1 goes into, etc. At any time if the sum of one set is half the total, you're done- success. At any time if the sum of one set is more than half the total, that sub-tree is a failure and you have to back up. At that point it is a tree traversal problem.

提交回复
热议问题