Python 排列回溯 - 为什么我必须在此回溯示例中调用 list?
在下面的代码中,为什么我需要在基本情况下调用 list() ?如果我不调用 current_perm 上的列表,它只会返回一个空列表的列表。
permutations = []
# returns a list of its permutation
def permutation(nums, current_perm = []):
if len(nums) == 0:
# must call list on current_perm
# not sure why
permutations.append(list(current_perm))
else:
for idx, num in enumerate(nums):
current_perm.append(num)
# pass nums as nums without the current number
permutation(nums[:idx]+nums[idx+1:], current_perm)
# backtrack
current_perm.pop()
In the code blow why do I need to call list() in the base case? If I don't call the list on current_perm, it just returns a list of empty lists.
permutations = []
# returns a list of its permutation
def permutation(nums, current_perm = []):
if len(nums) == 0:
# must call list on current_perm
# not sure why
permutations.append(list(current_perm))
else:
for idx, num in enumerate(nums):
current_perm.append(num)
# pass nums as nums without the current number
permutation(nums[:idx]+nums[idx+1:], current_perm)
# backtrack
current_perm.pop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论