MENU

第五届蓝桥杯 Java B—— 扑克序列

March 9, 2019 • Read: 3331 • 算法阅读设置

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;
  • }
  • }
Archives Tip
QR Code for this page
Tipping QR Code