【发布时间】:2018-12-05 10:20:43
【问题描述】:
我有一些问题需要在不使用任何模块的情况下递归解决,请您指导我。
你被放置在原点 (0, 0) 的格子板上,你想到达目的地 n,k(即 n 向右移动,k 向上移动)。我们一次只能向右或向上移动一步。实现一个函数,接收两个数字 n, k 并打印所有到达目的地 n, k 的路径,仅通过向右或向上步进。向上一步用“u”表示,向右用“r”表示。每条路径都必须是一系列字符 u、r,并且每条路径都必须打印在一行中。
我已经尝试过做某事:
def paths_ur(n, k):
paths_ur_helper(n, k, 0, 0)
def paths_ur_helper(n, k, right_moves, up_moves):
if right_moves == n and up_moves == k: #If we reach the destination there is nothing to return
return []
if right_moves < n and up_moves < k: #Check that we are in range of the board
return 'r' + paths_ur_helper(n, k, right_moves + 1, up_moves) +
\ +'u' + paths_ur_helper(n, k, right_moves, up_moves + 1)
但它出错了,可能是因为我没有正确想象递归的工作方式......
谢谢。
【问题讨论】:
标签: python-3.x recursion combinations recursive-backtracking