import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<>(); int curNumber = 0; int number = in.nextInt(); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int a = in.nextInt(); if(a % 5 == 0)curNumber += a; else if(a % 3 == 0)curNumber -= a; else list.add(a); } System.out.print(equals(list,curNumber)); } public static boolean equals(ArrayList<Integer> list,int curNumber){ if(list.size() == 0 && curNumber == 0) return true; else if(list.size() == 0) return false; int a = list.remove(0); if(equals(list,curNumber + a))return true; if(equals(list,curNumber - a))return true; list.add(0,a); return false; } }
简单思路理解
可以看作是天平上的重量需要一致,也就是天平左侧的重量-天平右侧的重量为0
5的倍数必须要放在天平左边,3的倍数必须放在右边,也就是这些数字在表达式中的符号已经被确定了。
剩下的确定剩余数字的符号,使得最终表达式的结果为0,数字的符号只有+,-两种,因此,用两条线递归即可