牛客网 雀魂启动

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func convInts(ss []string) []int {
	result := make([]int, len(ss))
	for i, v := range ss {
		res, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			panic(err)
		}

		result[i] = int(res)
	}

	return result
}

func check3s(cardMap map[int]int, remainCards int) bool {
	//fmt.Println(remainCards, cardMap)

	if remainCards == 0 {
		return true
	}
	for i := 1; i <= 9; i++ {
		cnt, ok := cardMap[i]
		if !ok || cnt == 0 {
			continue
		}

		//check 3
		if cnt >= 3 {
			cardMap[i] -= 3
			ok := check3s(cardMap, remainCards-3)
			cardMap[i] += 3
			if ok {
				return ok
			}
		}

		//check seq
		res1, _ := cardMap[i+1]
		res2, _ := cardMap[i+2]
		if res1 > 0 && res2 > 0 {
			cardMap[i]--
			cardMap[i+1]--
			cardMap[i+2]--
			ok := check3s(cardMap, remainCards-3)
			cardMap[i]++
			cardMap[i+1]++
			cardMap[i+2]++
			if ok {
				return ok
			}
		}
	}

	return false
}

func match(cards []int) []int {
	need := make([]int, 0)

	cardMap := make(map[int]int)
	appears := make(map[int]struct{})
	for _, v := range cards {
		cardMap[v]++
		appears[v] = struct{}{}
	}

	for i := 1; i <= 9; i++ {
		if res, ok := cardMap[i]; ok && res == 4 {
			continue
		}

		//fmt.Println("adding cards", cards, i, cardMap)

		cardMap[i]++
		appears[i] = struct{}{}
		for k := range appears {
			if cardMap[k] < 2 {
				continue
			}

			cardMap[k] -= 2
			ok := check3s(cardMap, 12)
			//fmt.Println("after", cardMap)
			cardMap[k] += 2
			if ok {
				need = append(need, i)
			}
		}

		cardMap[i]--
		if cardMap[i] == 0 {
			delete(cardMap, i)
			delete(appears, i)
		}
	}

	return need
}

func main() {
	rd := bufio.NewReader(os.Stdin)

	s, _ := rd.ReadString('\n')
	s = strings.TrimSpace(s)
	ss := strings.Split(s, " ")
	is := convInts(ss)

	if len(is) != 13 {
		panic(is)
	}

	need := match(is)
	if len(need) == 0 {
		fmt.Println("0")
	} else {
		for i := 0; i < len(need)-1; i++ {
			fmt.Printf("%d ", need[i])
		}
		fmt.Printf("%d\n", need[len(need)-1])
	}
}

你可能感兴趣的:(leetcode)