使用HashSet去重后,为啥只能过3个样例哇?
查看原帖
使用HashSet去重后,为啥只能过3个样例哇?
922560
smallrong楼主2023/12/6 10:36

我想知道为啥这段代码只能过3个样例



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;

public class Main {
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static int n, k;
    static int N = 25;
    static int[] arr = new int[N];
    static boolean[] st = new boolean[N];
    static HashSet<Integer> set= new HashSet<>();

    public static void main(String[] args) throws IOException {
        String[] s = in.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        k = Integer.parseInt(s[1]);
        s = in.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(s[i]);
        }
        bfs(0,0);
        System.out.println(set.size());
    }

    private static  void bfs(int x,int len){
        if (len==k){
            if (isprime(x)){
                set.add(x);
            }
        }
        for (int i = 0; i < n; i++) {
            if (!st[i]){
                st[i]=true;
                bfs(x+arr[i],len+1);
                st[i]=false;
            }
        }
    }

    private static boolean isprime(int x) {
        for (int i = 2; i * i <= x; i++) {
            if (x%i==0)
                return false;
        }
        return true;
    }
}
2023/12/6 10:36
加载中...