MENU

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

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

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