有沒有人瞭解下列用於產生數字列表的所有排列的迭代算法?Python非遞歸排列
我不明白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
我只是想了解上面的代碼。
你有沒有嘗試用調試器通過它?理解算法的好方法。 – FujiApple