当存在 sum5 + x = sum3 + y 时符合题意 x + y = sunOther; sum5 - sum3 + sumOther = 2y; 只要在OtherList中只要找到y 就可以得到解。递归寻找y
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static boolean result = false;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int count = in.nextInt();
int[] number = new int[count];
for (int i = 0; i < count; i++) {
number[i] = in.nextInt();
}
System.out.println(findNumnerArray(number));
}
}
public static boolean findNumnerArray(int[] number) {
int sumOther = 0;
int sum5 = 0;
int sum3 = 0;
List<Integer> list = new ArrayList<>();
for (int temp : number) {
if (temp % 5 == 0) {
sum5 = sum5 + temp;
} else if (temp % 3 == 0) {
sum3 = sum3 + temp;
} else {
sumOther = sumOther + temp;
list.add(temp);
}
}
int target = (sum5 - sum3 + sumOther) / 2;
if ((sum5 + sum3 + sumOther) % 2 != 0) return false;
dfs(list, target, 0);
return result;
}
public static void dfs (List<Integer> list, int target, int index) {
if (index == list.size()) {
if (target == 0) result = true;
return;
}
dfs(list, target - list.get(index), index + 1);
dfs(list, target, index + 1);
}
}