33分java代码求助 谢谢各位佬
查看原帖
33分java代码求助 谢谢各位佬
1403545
wwq666楼主2024/7/23 18:18

代码如下 去重的部分我没有用Arrays.sort()排序后,根据相邻值比较进行去重 而是使用了Set进行结果集的去重 拜托各位佬~

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        int[] nums = new int[20];
        for (int i = 0; i < n; i++) {
            nums[i] = scanner.nextInt();
        }
        Set<List<Integer>> res = new HashSet<>();
        func(nums, 0, n, new ArrayList<>(), k, res);
        System.out.println(res.size());
    }
    public static void func(int[] nums, int index, int n, List<Integer> list, int k, Set<List<Integer>> res ) {
        if (list.size() == k && isSuShu(sum(list))) {
            Collections.sort(list);
            res.add(list);
        }
        if (list.size() > k) {
            return;
        }
        for (int i = index; i < n; i++) {
            list.add(nums[i]);
            func(nums, i + 1, n, list, k, res);
            list.remove(list.size() - 1);
        }
    }
    public static int sum(List<Integer> list) {
        int res = 0;
        for (Integer integer : list) {
            res += integer;
        }
        return res;
    }
    public static boolean isSuShu(int num) {
        if (num <= 1) {
            return false;
        }
        if (num == 2) {
            return true;
        }
        if (num % 2 == 0) {
            return false;
        }
        for (int i = 3; i <= Math.sqrt(num); i += 2) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}
2024/7/23 18:18
加载中...