题解 | #雀魂启动!#

雀魂启动!

http://www.nowcoder.com/practice/448127caa21e462f9c9755589a8f2416


public class Main{
    
    
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        int[] map = new int[10];
        for(int i=0; i < 13; i++){
            int num = sc.nextInt();
            map[num]++;
        }
        for(int i=1; i < 10; i++){
            if(map[i] >= 4){
                continue;
            }
            map[i]++;
            for(int j = 1; j < 10; j++){
                //取雀头
                if(map[j] >= 2){
                    map[j] = map[j] - 2;
                    backTracking(map, i);
                    map[j] = map[j] + 2;
                }
            }
            map[i]--;
        }
        if (set.isEmpty()){
            System.out.println(0);
        }else{
            for (int val : set){
                System.out.print(val);
                System.out.print(" ");
            }
        }
    }

    static Set<Integer> set = new HashSet<>();

    public static void backTracking(int[] map, int cur){


        int sum = countMap(map);
        if (sum < 3)
            return;
        if(sum == 3){
            if (isOk(map))
                set.add(cur);
            return;
        }
        for(int j = 1; j < 10; j++){
            //取顺子
            if(map[j] >= 3){
                map[j] = map[j] - 3;
                backTracking(map, cur);
                map[j] = map[j] + 3;
            }
        }

        for (int i = 1; i < 8;i++) {
            if (map[i] > 0 && map[i+1] > 0 && map[i+2] > 0){
                map[i]--;
                map[i+1]--;
                map[i+2]--;
                backTracking(map, cur);
                map[i]++;
                map[i+1]++;
                map[i+2]++;
            }
        }
    }

    public static int countMap(int[] map){

        int sum = 0;
        for(int j = 1; j < 10; j++){
            sum += map[j];
        }
        return sum;
    }

    public static boolean isOk(int[] map){

        List<Integer> list = new ArrayList<>();
        for(int j = 1; j < 10; j++){
            for(int k = 0; k < map[j]; k++){
                list.add(j);
            }
        }
        if(list.size() != 3){
            return false;
        }
        Collections.sort(list);
        if (list.get(0) == list.get(1) && list.get(1) == list.get(2)){
            return true;
        }
        if (list.get(0) + 1 == list.get(1) && list.get(1) + 1 == list.get(2)){
            return true;
        }
        return false;
    }
}
全部评论

相关推荐

01-29 16:08
已编辑
华南农业大学 Java
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务