藍橋杯 DFS第四屆Java C組 第二題 求素數 個數

藍橋杯 DFS第四屆Java C組 第二題 求素數 個數

思路

根據主觀判斷,dfs枚舉所有可能性,使用check() 函數進行條件判斷,如果true,count++,記得無論什麼情況都
打印看一下,dfs枚舉可能性要考慮重複是否影響結果

代碼

import java.util.*;
public class two {
	static int[] list = { 1, 9, 4, 9 };
	static int count=0;
	public static HashSet<Integer> set=new HashSet<Integer>();
	public static void main(String[] args) {
		dfs(0);
		System.out.println(set.size());
		System.out.println(set);
	}

	public static void dfs(int pos) {
		if (pos == 4) {
			if (check())
				count++;
			return;
		} else {
			for (int i = pos; i < 4; i++) {
				swap(i, pos);
				dfs(pos + 1);
				swap(i, pos);
			}
		}
	}

	public static void swap(int a, int b) {
		int tmp = list[a];
		list[a] = list[b];
		list[b] = tmp;
	}

	public static boolean check() {
		int sum=0;
		for(int i =0;i<4;i++) {
			sum=sum*10+list[i];
		}
		for(int i=2;i<sum;i++) {
			if(sum%i==0)return false;
		}
		set.add(sum);
		return true;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章