题解 | #数组分组#

数组分组

https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86

import java.util.*;
public class Main{
  public static void main(String[] args){
      Scanner in = new Scanner(System.in);
      
          //根据输入计算sum3,sum5和所有数总和sum,同时把不是5和3倍数的剩余数放入集合
      LinkedList<Integer> list = new LinkedList<>();
          int n = in.nextInt();
          int sum5=0, sum3=0, sum = 0;
          for (int i = 0; i < n; i++){
              int cur = in.nextInt();//输入
              if (cur % 5 == 0){//5倍数和
                  sum5 += cur;
              }else if (cur % 3 == 0){//3倍数和
                  sum3 += cur;
              }else{//剩余加入集合
                  list.add(cur);
              }
              sum += cur;//总和
            }
          

          //特例,总和不是2的倍数,不可分2份和相等的数字
          if(sum%2!=0) System.out.print("false");
          else{System.out.print(bt(list,sum/2,sum3,0));}
      
    }
        static boolean bt(LinkedList<Integer> list,int tar,int buc,int start){
            if(buc==tar){
                return true;
            }
            for(int i=start;i<list.size();i++){
                buc+=list.get(i);
                if(bt(list,tar,buc,i+1)){return true;}
                buc-=list.get(i);
            }
            return false;
        }


}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务