【字节跳动实习面试 2019-01-07】

一、题目描述

给定长度为14的整型数组,判断是否胡牌2 + 3*4   dd + (abc or aaa) * 4
范围 1~9之间代表数字1~9
形如 111 222 333 456 77  返回True
形如 111 223 345 67 999  返回True
形如 111 222 333 457 99 返回False

二、解题思路

把规则拆分开,分开讨论,不可能一个式子包括所有情况的

from collections import Counter
def is_agari(tehai) -> bool:
    def is_agari_impl(tehai_cnt: Counter, rest_tiles: int) -> bool:
""" Args:tehai_cnt: 各种牌的枚数信息rest_tiles: 剩余手牌张数 """
        if rest_tiles == 0:
            return True
        min_tile = min(filter(lambda x: tehai_cnt[x], tehai_cnt.keys()))
        # 拆刻子(aaa)
        if tehai_cnt[min_tile] >= 3:
            tehai_cnt[min_tile] -= 3
            if is_agari_impl(tehai_cnt, rest_tiles - 3):
                return True
            tehai_cnt[min_tile] += 3
        # 拆雀头(对子,即dd)
        if rest_tiles % 3 and tehai_cnt[min_tile] >= 2:
            tehai_cnt[min_tile] -= 2
            if is_agari_impl(tehai_cnt, rest_tiles - 2):
                return True
            tehai_cnt[min_tile] += 2
        # 拆顺子(abc)
        if (min_tile < 27 and min_tile % 9 < 7
                and tehai_cnt[min_tile + 1] and tehai_cnt[min_tile + 2]):
            tehai_cnt[min_tile] -= 1
            tehai_cnt[min_tile + 1] -= 1
            tehai_cnt[min_tile + 2] -= 1
            if is_agari_impl(tehai_cnt, rest_tiles - 3):
                return True
            tehai_cnt[min_tile + 2] += 1
            tehai_cnt[min_tile + 1] += 1
            tehai_cnt[min_tile] += 1
        return False

    return is_agari_impl(Counter(tehai), len(tehai)) if len(tehai) % 3 == 2 else False
if __name__ == '__main__':
   # tehai = [0,0,0,1,2,3,4,5,6,7,8,8,8,8]
   tehai = [1,1,1,2,3,4,2,3,4,5,6,8,9,9]