题解 | #数组分组#
数组分组
http://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
//参考网友ld1230的解法 //思想:将能整除3或者5的各自分为一组,记为sum1和sum2,剩余的保存在数组nums里 //现有两组,剩余nums里的数要么在sum1里要么在sum2里,利用递归依次放在sum1和sum2中 //最终nums里的数字全部放进去,若sum1 == sum2,则返回true,否则,返回false let str; while(str = readline()){ let num = readline(); let arr = num.split(' '); let three = arr.filter((v)=>{ return v%3==0 && v%5!=0; }) let five = arr.filter((v)=>{ return v%5==0; }) let other = arr.filter((v)=>{ return v%5!=0 &&v%3!=0; }) //所有三的倍数的数字的和 let tsum = three.reduce((pre,cur)=>{ return pre+cur*1; },0) //所有五的倍数的数字的和 let fsum = five.reduce((pre,cur)=>{ return pre+cur*1; },0) console.log(isExists(tsum,fsum,other,0)) } function isExists(sum1,sum2,nums,index){ if(index == nums.length && sum1 != sum2) return false; if(index == nums.length && sum1 == sum2) return true; if(index < nums.length) return isExists(sum1+parseInt(nums[index]), sum2, nums, index+1) || isExists(sum1, sum2+parseInt(nums[index]), nums, index+1); return false; }