《程序员的算法趣题》-(日)增井敏克 Python解题 -- (Q24)

《程序员的算法趣题》-(日)增井敏克 , 书中为69 道数学谜题编写了解题程序, 编程语言为:Ruby,JavaScript,C语言。有兴趣的同学,可以购书阅读~

在此更新个人编写的Python版,仅供学习使用。(运行环境:Python3.6)

Q24 完美的三振出局

    对喜爱棒球的少年而言,“三振出局”是一定要试一次的。这是一个在本垒上放置 9 个靶子,击打投手投来的球,命中靶子的游戏。据说这可以磨练球手的控制力。

                                                           
    现在来思考一下这 9 个靶子的击打顺序。假设除了高亮的 5 号靶子以外,如果 1 个靶子有相邻的靶子,则可以一次性把这 2 个靶子都击落。譬如,如下图所示,假设 1 号、 6 号、 9 号已经被 击 落 了, 那 么 接 下 来, 对 于“2 和3”“4 和 7”“7 和 8”这 3 组靶子,我们就可以分别一次性击落了。

                                                           

问题
    求 9 个靶子的击落顺序有多少种?这里假设每次投手投球后,击球手都可以击中一个靶子。

hit_possible_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,
                     (1, 2), (2, 3),
                     (4, 1), (6, 3),
                     (7, 4), (9, 6),
                     (8, 7), (9, 8)]

calculate_map = {}

def baseball_game(rest_ball):
    if len(rest_ball) == 0:
        return 1
    elif rest_ball in calculate_map:
        return calculate_map[rest_ball]
    result = 0
    for hit in hit_possible_list:
        if type(hit) is tuple:
            if hit[0] in rest_ball and hit[1] in rest_ball:
                new_rest_ball = tuple(i for i in rest_ball if i != hit[0] and i != hit[1])
                result += baseball_game(new_rest_ball)
        else:
            if hit in rest_ball:
                new_rest_ball = tuple(i for i in rest_ball if i != hit)
                result += baseball_game(new_rest_ball)

    calculate_map[rest_ball] = result

    return result

print("有%s种" % baseball_game((1, 2, 3, 4, 5, 6, 7, 8, 9)))

运行结果:

                 有798000种

猜你喜欢

转载自blog.csdn.net/cloudly89/article/details/84998063