题目:
思路:
现在需要让arr3和arr5两个数组中的和相等,就需要将other数组中的数分配到两个数组中,假设分配x到arr5中,分配y到arr3数组中,那么需要满足如下关系式。需要满足公式:
1:sum5 + x = sum3 + y
2:x + y = othersum
转换得到:
1:sum5 - sum3 = y - x
2:other = x + y
两个公式相加:sum5 - sum3 + other = 2*y
进一步可以推出:
y = (sum5 - sum3 + other)/2
所以只需要找到存在一个或多个数相加的结果满足y
提交:
let line
while(line = Number(readline())) {
let arr = readline().split(' ')
let sum3 = 0
let sum5 = 0
let otherSum = 0
let other = []
arr.forEach(item => {
if (Number(item) % 3 === 0) {
sum3 += Number(item)
} else if (Number(item) % 5 === 0) {
sum5 += Number(item)
} else {
otherSum += Number(item)
other.push(Number(item))
}
})
/**
* y为输入数组的一部分
* 求 y * 2 = sum5 - sum3 + otherSum
* params: {
* other: [] 存储数字,累加可构成y
* visited: [] 标识是否遍历过了 每次用完要恢复现场
* target: y
* }
* */
function dfs(index, other, visited, target) {
// console.log(...arguments)
// 退出条件
if (target === 0) {
return true
} else {
let length = other.length
for (let i = index; i < length; i++) {
if (!visited[i]) {
visited[i] = true
if (dfs(i + 1, other, visited, target - other[i])) {
return true
}
visited[i] = false
}
}
return false
}
}
let temp = sum5 - sum3 + otherSum
// console.log('temp', temp)
// y是否为整数
if (temp % 2 === 0) {
let target = temp / 2
let visited = new Array(other.length).fill(false)
// y是否在数组里能找到
console.log(dfs(0, other, visited, target))
} else {
console.log(false)
}
}