How do you divide the elements in list into two parts so that the two parts are the same (if there is such a partition)?

suppose there are n elements in the list, how to divide the list into two parts list1,list2, to make it sum (list1) = = sum (list2), if there is such a partition, otherwise return-1. (the partition here means to pick)

Apr.07,2021

knapsack problem, first add once to get sum (all), and then the knapsack limit is sum (all) / 2, which can be solved by using dynamic programming algorithm or search algorithm.


it always feels as if there is something wrong, but I have tried many sets of data, and the results are all correct.

function sumArray(arr){
  var length = arr.length
  var sum = 0
  for(var i = 0;i<length;iPP){
    sum += arr[i] 
  }
  
  return sum
}

function blanceArray(left,right){
  console.log('==========================')
  console.log(left,right)
  var leftsum = sumArray(left)
  var rightsum = sumArray(right)
  console.table(leftsum,rightsum)
  if(leftsum>rightsum){
    return false
  }
  if(leftsum === rightsum){
    return [left,right]
  } else {
    var findnum = (rightsum-leftsum)/2
    for(var i = 0;i<=right.length;iPP){
      if(right[i]===findnum){
        left.push(...right.splice(i,1))
        return [left,right]
      }
    }
    left.push(right.pop())
    return blanceArray(left,right)
  }
  
}

function main(arr){
  var sum = sumArray(arr)
  console.log(sum)
  if(sum % 2 !== 0){
    return false
  }
  
  arr.sort(function(a,b){
    return a<b
  })
  
  
  
  var left = [arr.shift()]
  //console.log(arr)
  return blanceArray(left,arr)
  
}

//var testarr = [2,5,6,7,8,4]
var testarr = [3,2,4,3]
var testarr = [1,3,3,6,7,8,16,2]

var result = main(testarr)

console.log(result)

http://jsbin.com/yipuxajala/1.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e51fb0-444cf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e51fb0-444cf.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?