【面试】麻将胡牌【字节跳动】【游戏规则】【递归】

172 篇文章 4 订阅
5 篇文章 1 订阅

【字节跳动实习面试 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]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值