递归回溯算法中未更改变量

时间:2019-07-08 16:02:56

标签: python recursion dynamic-programming backtracking

我正在使用递归和回溯来解决问题。每当满足特定条件时,我都会更新名为minimum的变量。但是,尽管在函数返回时minimum变量被更新了几次,但minimum仍被设置为其原始值。

我不明白为什么,因为我要传递对内存中同一位置的引用,并在遇到基本情况时对其进行更新。

def minCost(self, costs: List[List[int]]) -> int:
        depth, cost, prev_index, minimum = 0, 0, None, 10000

        def min_cost_recur(depth, cost, prev_index, n, minimum, costs):
            if depth == n:
                minimum = min(minimum, cost)
                return

            original_prev_index = prev_index*1

            for i in range(0, 3):
                if not i == original_prev_index:
                    cost += costs[depth][i]
                    depth += 1
                    prev_index = i
                    min_cost_recur(depth, cost, prev_index, n, minimum, costs)
                    depth-=1
                    cost -= costs[depth][i]
                    prev_index = original_prev_index

        min_cost_recur(depth, cost, -1, len(costs), minimum, costs)

        return minimum

1 个答案:

答案 0 :(得分:0)

您应该在递归中返回minimum的新值,否则它将永远不会更新:

def minCost(self, costs: List[List[int]]) -> int:
        depth, cost, prev_index, minimum = 0, 0, None, 10000

        def min_cost_recur(depth, cost, prev_index, n, minimum, costs):
            if depth == n:
                minimum = min(minimum, cost)
                return minimum

            original_prev_index = prev_index*1

            for i in range(0, 3):
                if not i == original_prev_index:
                    cost += costs[depth][i]
                    depth += 1
                    prev_index = i
                    minimum = min(minimum, min_cost_recur(depth, cost, prev_index, n, minimum, costs))
                    depth-=1
                    cost -= costs[depth][i]
                    prev_index = original_prev_index
            return minimum
        minimum = min_cost_recur(depth, cost, -1, len(costs), minimum, costs)

        return minimum

之所以会这样,是因为minimum不是通过引用而是通过值传递的,因为它是不可变类型的实例。当您在递归中修改它的值时,它只是创建一个最小的本地nmae,而不是从父作用域更改变量。