题解 | #数组分组#递归,纯粹为了好理解

数组分组

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;
  }
}

#华为机试#
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:10
点赞 评论 收藏
分享
05-29 09:02
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 10:39
一个证都没&nbsp;我能填什么
程序员小白条:别人有,你为什么没有,还是这个道理,社会就是比较,竞争,淘汰,你要安逸,那么就要做好淘汰的准备
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务