题解 | 汉诺塔问题

汉诺塔问题

https://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param n int整型 
# @return string字符串一维数组
#
class Solution:
    def getSolution(self , n: int) -> List[str]:
        # write code here
        # 21:57
        def solver(n, source,target,through):
            if n == 0:
                return []
            else:
                moves = solver(n-1, source, through, target) # 先通过target把前面n-1个从source搬到through
                moves = moves + [f'move from {source} to {target}'] # 再把最后一个盘子从source搬到target
                moves = moves + solver(n-1,through,target,source)# 再把n-1个还在through的盘子搬到target通过source
                return moves
        return solver(n,'left','right','mid')

        

全部评论

相关推荐

09-09 11:13
南京大学 Java
点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
09-13 11:00
门头沟学院 Java
只A了第一题.....
投递中国电信等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务