python在递归函数中的传参问题

python中递归函数传参

有 d 个一样的骰子,每个骰子上都有 f 个面,分别标号为 1, 2, ..., f。
我们约定:掷骰子的得到总点数为各骰子面朝上的数字的总和。
如果需要掷出的总点数为 target,请你计算出有多少种不同的组合情况(所有的组合情况总共有 f^d 种),模 10^9 + 7 后返回

在解题的过程中用到了递归,刚开始定义了一个外部变量count

    def numRollsToTarget(self, d, f, target):
        """
        :type d: int
        :type f: int
        :type target: int
        :rtype: int
        """
        candidates = range(1, f + 1, 1)
        count = 0
        result = []

        def DFS(candidates, count, result, target):
            if (target - sum(result) < 0):
                return
            elif ((target - sum(result) == 0) and (len(result) == d)):
                # results.append(copy.deepcopy(result))	#使我们要的,就把数据添加到结果中去
                count = count + 1
                return count

            for i in candidates:
                # if i >= current:  # 一方面保证没有重复的数据集,另一方面保证每一个元素,排序是从小到大
                result.append(i)  # 试图添加一个点
                DFS(candidates, count, result, target)  # 继续遍历并判断是否满足条件
                result.pop()  # 进行回退

        DFS(candidates, count, result, target)
        return count

得到的结果一直为0。这是因为在传递

这里涉及到python的传参机制问题,python不允许用户在函数的参数传递中选择是值传递还是引用传递,而是采用的对象引用传递,如果函数收到的是一个可变对象(如列表或字典)的引用,就采用引用传递。而如果收到的是一个不可变对象(如数字,字符和元组等)的引用,就采用值传递。在函数中将无法改变参数的原始值。

下面将count重新定义为一个可变对象后,就可以返回正确的结果

    def numRollsToTarget(self, d, f, target):
        """
        :type d: int
        :type f: int
        :type target: int
        :rtype: int
        """
        candidates = range(1, f + 1, 1)
        count = [0]
        result = []

        def DFS(candidates, count, result, target):
            if (target - sum(result) < 0):
                return
            elif ((target - sum(result) == 0) and (len(result) == d)):
                # results.append(copy.deepcopy(result))	#使我们要的,就把数据添加到结果中去
                count[0] = count[0] + 1
                return count

            for i in candidates:
                # if i >= current:  # 一方面保证没有重复的数据集,另一方面保证每一个元素,排序是从小到大
                result.append(i)  # 试图添加一个点
                DFS(candidates, count, result, target)  # 继续遍历并判断是否满足条件
                result.pop()  # 进行回退

        DFS(candidates, count, result, target)
        return count[0]
发布了46 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/li123_123_/article/details/99203165
今日推荐