题解 | 汉诺塔问题
汉诺塔问题
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')
腾讯成长空间 1169人发布