简体   繁体   English

回溯解决方案中的变量值不会回到其原始 state

[英]variable value in a backtracking solution is not going back to its original state

I was trying to build a solution to the problem of generating all possible combination of k of the length n我试图构建一个解决方案来解决生成长度为nk的所有可能组合的问题

ex: k = 4, n = 2例如:k = 4,n = 2

output: output:

[1, 1]
[1, 2]
[1, 3]
[1, 4]
[2, 1]
[2, 2]
[2, 3]
[2, 4]
[3, 1]
[3, 2]
[3, 3]
[3, 4]
[4, 1]
[4, 2]
[4, 3]
[4, 4]

Here is the pseudocode for the logic that I implemented这是我实现的逻辑的伪代码

def backTrack(arr):
    if length(arr) == k:
        return

    loop through from 1 to n <- for i in range(1, n+1):
        i = value of loop
        add i to an array variable arr <- arr.append(i)
        backtrack(arr) <- recurse
        remove last index value from arr <- arr = arr[:-1]

for this above code, I am supposed to get the following values对于上面的代码,我应该得到以下值

on depth 1:
   the loop starts with 1
   and arr = [1]
   
   then it recuses to depth 2
      the loop starts with 1
       and arr = [1, 1]
       since the length of arr = k =2 it wont recurse further and continue
       arr = arr[:-1] = arr = [1]

       then i will be 2 
       and arr = [1,2]
       similarly [1, 3] and [1, 4] and then it goes to depth 1 or the parent call

on depth 1
  value of i = 1
   and arr  = 1
   now, arr = arr[:-1] that makes arr = []
  and now i becomes 2 and the process continues
       

But debugging the code written with the following pseudo code, shows that on depth 1 the arr never get back to being [1] but become [1, 1] I am still struggling to understand why it is so.但是调试用以下伪代码编写的代码表明,在深度1上,arr 永远不会恢复为[1]而是变为[1, 1]我仍在努力理解为什么会这样。

Below is the debugging solution with the print statements以下是带有打印语句的调试解决方案

class Solution(object):
    def combine(self, n, k):
    
        def backTrack(arr, result, depth):
            if len(arr) == k:
                return
    
            for i in range(1, n + 1):
                arr.append(i)
                print("depth = " + str(depth) + ", i = " + str(i) + ", arr=" + str(arr))
                backTrack(arr, result, depth + 1)
            
                print("depth -> " + str(depth) + ", i-> " + str(i) + ", arr-> " + str(arr))
                arr = arr[:-1]

        
        return backTrack([], [], 1)



ob = Solution()
result = ob.combine(4, 2)

Below is the debugged output下面是调试后的output

depth = 1, i = 1, arr=[1]
depth = 2, i = 1, arr=[1, 1]
depth -> 2, i-> 1, arr-> [1, 1]
depth = 2, i = 2, arr=[1, 2]
depth -> 2, i-> 2, arr-> [1, 2]
depth = 2, i = 3, arr=[1, 3]
depth -> 2, i-> 3, arr-> [1, 3]
depth = 2, i = 4, arr=[1, 4]
depth -> 2, i-> 4, arr-> [1, 4]
depth -> 1, i-> 1, arr-> [1, 1] * going back to parent call arr never becomes 1
depth = 1, i = 2, arr=[1, 2]
depth -> 1, i-> 2, arr-> [1, 2]
depth = 1, i = 3, arr=[1, 3]
depth -> 1, i-> 3, arr-> [1, 3]
depth = 1, i = 4, arr=[1, 4]
depth -> 1, i-> 4, arr-> [1, 4]

I have marked the debugger output in * to show the state of the arr in the parent call never gets back to being 1我在*中标记了调试器 output 以显示父调用中 arr 的 state 永远不会恢复为1

I want to understand why it is so.我想了解为什么会这样。

arr = arr[:-1] creates a new copy of arr with the last element removed and assigns it to the local variable arr . arr = arr[:-1]创建arr新副本,其中最后一个元素被删除,并将其分配给局部变量arr This means that the arr s in other scopes of the recursive calls reference some other list which still has the last element.这意味着递归调用的其他范围内的arr引用了仍然具有最后一个元素的其他列表。

You need to remove the last element from this list by writing arr.pop() .您需要通过编写arr.pop()从此列表中删除最后一个元素。

If you need further explanation about mutable and immutables in python and why it works this way please comment.如果您需要进一步解释 python 中的可变和不可变以及为什么它以这种方式工作,请发表评论。

This is how the implementation should look like based on your pseudo-code:根据您的伪代码,实现应该是这样的:

class Solution(object):
    def combine(self, n, k):
        total = []

        def backTrack(depth, stack):
            if depth >= k:
                total.append(stack[:])
                return

            for i in range(1, n + 1):
                stack.append(i)
                backTrack(depth + 1, stack)
                stack.pop()

        backTrack(0, [])
        return total

In your implementation this line of code arr = arr[:-1] does not remove anything from the list.在您的实现中,这行代码arr = arr[:-1]不会从列表中删除任何内容。 In fact, it brakes the whole list by making it equal with the last element.事实上,它通过使其与最后一个元素相等来阻止整个列表。

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

相关问题 如何将反向列表返回到 python 中的原始 state - How to return a reversed list back to its original state in python 如何用新的字符串替换数组中的特定索引,然后将其恢复为原始值? - How to replace a specific index inside of an array with a new string, and then revert it back to its original value? 如何在python中将列表返回到其原始状态? - how to return a list to its original state in python? 方法将变量返回其原始参数变量 - Method returns variable into its original parameter variable 如何在不返回 0 的情况下增加变量 - How to increment a variable without it going back to 0 “自我”如何正确更新原始变量? N-皇后问题中的递归/回溯(Python) - How can "self" update original variable correctly? Recursion/Backtracking in the N-queens problem (Python) 为什么在按下按钮(Tkinter)之后变量会恢复为原始值? - Why does the variable revert back to original value after button is pressed (Tkinter)? 如何在不更改 python 中的原始值的情况下将二维数组中的元素分配给新变量? - How to assign an element from a 2D array to a new variable without changing its original value in python? 如何在保留变量原始值的同时拆分和重建它 - How do I split and reconstruct a variable name while holding its original value 回溯-生成计划的解决方案提示 - backtracking - solution hint for generating schedule
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM