简体   繁体   English

Python递归问题【leetcode问题】

[英]Python recursion issue [leetcode problem]

在此处输入图片说明

Above is the question.以上是问题。 It is to find all the permutation in for given array of integers(all unqiue)它是在给定的整数数组中找到所有排列(所有unqiue)

Actual Question实际问题

I was trying out check the brute-force method permutation method( Not looking for the optimal solution ).我正在尝试检查蛮力方法排列方法(不寻找最佳解决方案)。 I found myself in this peculiar problem.我发现自己陷入了这个奇怪的问题。 The result array used to store the permutations changed with every recursion call.用于存储每次递归调用时更改的排列的结果数组。 I cannot put a head around it why is that.我无法理解它为什么会这样。 Need help figuring it out.需要帮助弄清楚。

I have included print() from different places of the code for debugging purpose.我在代码的不同位置包含了 print() 用于调试目的。 Let me know if you need any other information to help you reach an answer.如果您需要任何其他信息来帮助您找到答案,请告诉我。

Algorithm walkthrough算法演练

element_map -> stores False for each position of the input array [False,False,False] in this case temp_result -> stores temporary permutations in each step element_map -> 为输入数组的每个位置存储 False [False,False,False]在这种情况下temp_result -> 在每个步骤中存储临时排列

  1. permutation function iterates over every val of the input array and stores permutations in the temp_result array.置换函数迭代输入数组的每个 val 并将置换存储在temp_result数组中。
  2. Once an element is added to temp_result , it marks element_map as True and recursively calls permutation function again.将元素添加到temp_result 后,它将element_map 标记为 True 并再次递归调用排列函数
  3. End of recursion is if len(temp_result) == len(nums) .递归结束是 if len(temp_result) == len(nums) In that case, we got one permutation and we add it to result.在这种情况下,我们得到一个排列并将其添加到结果中。
  4. Once base case 3 is hit we set element_map[i] = False and pop the last val from temp_result一旦遇到基本情况 3,我们设置element_map[i] = False并从temp_result 中弹出最后一个 val
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        
        if len(nums) == 1:
            return [nums]
        
        result = []
        element_map = defaultdict(bool)
        for i in range(len(nums)):
            element_map[i] = False
        
        def permutations(nums, temp_result, element_map):
            nonlocal result
            print("Start result ->", result)
            print("Start temp_result ->", temp_result)
            
            if len(temp_result) == len(nums):
                result.append(temp_result)
                print(len(temp_result),len(nums))
                print("temp_result ->", temp_result)
                print("result-> ",result)
                return
            
            for i,val in enumerate(nums):
                
                if not element_map[i]:
                    element_map[i] = True
                    temp_result.append(val)
                    permutations(nums, temp_result, element_map)
                    temp_result.pop()
                    element_map[i] = False
        
        temp_result = []
        permutations(nums, temp_result, element_map)
        print(result)

Code Output for input [1,2,3].输入 [1,2,3] 的代码输出。 Issue is the result keeps changing.问题是结果不断变化。

Start result -> []
Start temp_result -> []
Start result -> []
Start temp_result -> [1]
Start result -> []
Start temp_result -> [1, 2]
Start result -> []
Start temp_result -> [1, 2, 3]
3 3
temp_result -> [1, 2, 3]
result->  [[1, 2, 3]]
Start result -> [[1, 3]]
Start temp_result -> [1, 3]
Start result -> [[1, 3, 2]]
Start temp_result -> [1, 3, 2]
3 3
temp_result -> [1, 3, 2]
result->  [[1, 3, 2], [1, 3, 2]]
Start result -> [[2], [2]]
Start temp_result -> [2]
Start result -> [[2, 1], [2, 1]]
Start temp_result -> [2, 1]
Start result -> [[2, 1, 3], [2, 1, 3]]
Start temp_result -> [2, 1, 3]
3 3
temp_result -> [2, 1, 3]
result->  [[2, 1, 3], [2, 1, 3], [2, 1, 3]]
Start result -> [[2, 3], [2, 3], [2, 3]]
Start temp_result -> [2, 3]
Start result -> [[2, 3, 1], [2, 3, 1], [2, 3, 1]]
Start temp_result -> [2, 3, 1]
3 3
temp_result -> [2, 3, 1]
result->  [[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]]
Start result -> [[3], [3], [3], [3]]
Start temp_result -> [3]
Start result -> [[3, 1], [3, 1], [3, 1], [3, 1]]
Start temp_result -> [3, 1]
Start result -> [[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
Start temp_result -> [3, 1, 2]
3 3
temp_result -> [3, 1, 2]
result->  [[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
Start result -> [[3, 2], [3, 2], [3, 2], [3, 2], [3, 2]]
Start temp_result -> [3, 2]
Start result -> [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
Start temp_result -> [3, 2, 1]
3 3
temp_result -> [3, 2, 1]
result->  [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
[[],[],[],[],[],[]]

I've written an alternative to your function.我已经为您的函数编写了一个替代方法。 I've tested this with Python2, but it should work with Python3 as well.我已经用 Python2 对此进行了测试,但它也应该适用于 Python3。

Arr = [1, 2, 3, 4, 5]

def permute(arr):
    myresult = []
    for i in range(len(arr)):
        sarr = arr[:i] + arr[i+1:]
        el = arr[i]
        if len(sarr) != 0:
            a = permute(sarr)
            for result in a:
                c = [el] + result
                myresult.append(c)
        else:
            return [[el]]
    return myresult

p = permute(Arr)
print str(p)

myresult is going to be the result of the permute function. myresult将是置换函数的结果。 sarr stands for the "smaller array". sarr代表“较小的数组”。 el stands for Element (of the Array). el代表元素(数组的)。

The idea is to pick an element and to concatenate each permutation of the remaining array.这个想法是选择一个元素并连接剩余数组的每个排列。 By using recursion the entire input array will be processed通过使用递归,将处理整个输入数组

Found the solution找到解决方案

if len(temp_result) == len(nums):
     result.append(temp_result[:])

instead of代替

if len(temp_result) == len(nums):
     result.append(temp_result)

In the latter result values changes with the value of temp_result .在后者中,结果值随temp_result的值而变化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM