第五屆藍橋杯Java B——撲克序列
A A 2 2 3 3 4 4, 一共4對撲克牌。請你把它們排成一行。
要求:兩個A中間有1張牌,兩個2之間有2張牌,兩個3之間有3張牌,兩個4之間有4張牌。
請填寫出所有符合要求的排列中,字典序最小的那個。
例如:22AA3344 比 A2A23344 字典序小。當然,它們都不是滿足要求的答案
import java.util.Set; import java.util.TreeSet; public class Main { static char[] arr = {'A','A','2','2','3','3','4','4'}; static char[] res = new char[8]; static int[] book = new int[8]; static Set<String> set = new TreeSet<String>(); public static void main(String[] args) { dfs(0); for (String s : set) System.out.println(s); } private static void dfs(int idx) { if (idx == 8) { if (check()) set.add(new String(res)); } else { for (int i = 0; i < 8; i++) if (book[i] == 0) { book[i] = 1; res[idx] = arr[i]; dfs(idx + 1); book[i] = 0; } } } static boolean check() { String str = new String(res); return str.lastIndexOf("A") - str.indexOf("A") == 2 && str.lastIndexOf("2") - str.indexOf("2") == 3 && str.lastIndexOf("3") - str.indexOf("3") == 4 && str.lastIndexOf("4") - str.indexOf("4") == 5; } }