题解 | #数组分组#递归,纯粹为了好理解
数组分组
https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
//递归,others第三组有两种情况,根本没有值,无须分配; 有值,需要全部分配完 const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let k=0; let n = 0; let nums = []; rl.on('line', function(line){ if(k === 0){ n = Number(line); k++; }else { nums = line.split(' ').map(e=> Number(e)); getArr(); } }); function getArr(){ let multi5 = []; let multi3 = []; let others = []; for(let i=0; i<nums.length; i++){ if(nums[i] % 3 === 0 && nums[i] % 5 !== 0){ multi3.push(nums[i]); }else if(nums[i] % 5 === 0){ multi5.push(nums[i]) }else { others.push(nums[i]); } } let sum5 = multi5.length >0 ? multi5.reduce((prev, current)=>prev+current) : 0; let sum3 = multi3.length > 0 ? multi3.reduce((prev, current)=>prev+current) : 0; console.log(isExists(sum5, sum3, others, 0)); } function isExists(sum5, sum3, others, index){ if(others.length === 0 && sum5 !== sum3){ return false; }else if(others.length === 0 && sum5 === sum3){ return true; }else if(others.length === index && sum5 !== sum3){ return false; }else if(others.length === index && sum5 === sum3){ return true; }else if(index < others.length){ return isExists(sum5+others[index], sum3, others, index+1) || isExists(sum5, sum3+others[index], others, index+1); }else { return false; } }
#华为机试#