【发布时间】:2016-08-17 04:03:08
【问题描述】:
有人了解以下用于生成数字列表的所有排列的迭代算法吗?
我不明白while len(stack) 循环中的逻辑。有人可以解释一下它是如何工作的吗?
# Non-Recursion
@param nums: A list of Integers.
@return: A list of permutations.
def permute(self, nums):
if nums is None:
return []
nums = sorted(nums)
permutation = []
stack = [-1]
permutations = []
while len(stack):
index = stack.pop()
index += 1
while index < len(nums):
if nums[index] not in permutation:
break
index += 1
else:
if len(permutation):
permutation.pop()
continue
stack.append(index)
stack.append(-1)
permutation.append(nums[index])
if len(permutation) == len(nums):
permutations.append(list(permutation))
return permutations
我只是想理解上面的代码。
【问题讨论】:
-
你试过用调试器单步调试吗?理解算法的好方法。
标签: python algorithm permutation