帮我康康-我是不是没有重复性剪枝
查看原帖
帮我康康-我是不是没有重复性剪枝
482655
黄诗宇楼主2021/2/25 09:18
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;


public class P1036 {
	static int cnt=0;
	static int n=0;
	static boolean IsPrime(int n) {
		if (n<=1) {
			return false;
		}
		for (int i = 2; i <=Math.sqrt(n); i++) {
			if(n%i==0)return false;
		}
		return true;
	}
	static ArrayList<Integer> num=new ArrayList<>();
	static ArrayList<Boolean> hash=new ArrayList<>();
	static Stack<Integer> stack =new Stack<>();
	static String s;
	static void dfS(int index) {
		if (index==n) {
			int sum=0;
			for (int e : stack) {
				sum+=e;
			}
			if (IsPrime(sum)) {
				cnt++;
			}
		}
		for (int i = index; i < num.size(); i++) {
			if (hash.get(i)) {
				continue;
			}
			hash.set(i, true);
			stack.push(num.get(i));
			dfS(index+1);
			stack.pop();
			hash.set(i, false);
		}
	}
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int max=scanner.nextInt();
		n=scanner.nextInt();
		for (int i = 0; i < max ; i++) {
			num.add(scanner.nextInt());
			hash.add(false);
		}
		Collections.sort(num);
		dfS(0);
		System.out.println(cnt);
	}
}

9 7

1 1 1 1 1 1 1 1 1

2187(正确答案36)

只要有相同的数字就要出错,到底是哪里重复统计了呢,有没有大佬帮我解释一下,跪谢!

2021/2/25 09:18
加载中...