Leetcode#77组合-不确定此语法有什么问题

问题描述

我正在尝试学习python,并且正在做leetcode问题以更加熟悉语法。我收到错误消息:

NameError: name 'dfs' is not defined
    dfs(result,temp,n,k)

我也不确定是否正确声明了列表,还是应该将self作为参数传递给函数

class Solution:
    def dfs(self,result: List[List[int]],temp:List[int],index: int,n: int,k: int):
        for i in range(index + 1,n + 1):
            temp.push(i)
            if len(temp) == k:
                result.push(temp)
                temp.pop()
                return 
            else:
                dfs(result,i,k)
                temp.pop()
                
    def combine(self,k: int) -> List[List[int]]:
        result = [[]];
        temp = [];
        dfs(result,k)
        return result

解决方法

应为self.dfs(result,temp,n,k)。因此,无论您在哪里使用self.dfs

,都应更改为dfs ,

在此示例中,dfsSolution上的一种方法,因此从Solution上的其他方法中使用它时,您想调用self.dfs而不是{{1} }。另外,您可以将dfs的定义移到类之外,如下所示:

dfs

我假设这些是类上的方法的原因与leetcode接口的格式有关,该格式要求使用类而不是独立的函数,但是对于def dfs(...): ... class Solution: ... ,在Python中可能更惯用在大多数情况下是独立功能而不是方法。通常,如果某些东西不需要使用dfs参数并且不需要被仅具有对特定对象的引用的东西调用,则无需将其设为方法。

,

使用itertools.combinations解决这些算法问题并不是最好的主意,但是以防万一,您可以在这里解决问题。

这将通过:

class Solution:
    def combine(self,k):
        return tuple(itertools.combinations(range(1,n + 1),k))

下面是LeetCode的一些带有注释的解决方案,它们实现了相同的想法:

class Solution:
    def combine(self,n: int,k: int) -> List[List[int]]:
        # init first combination
        nums = list(range(1,k + 1)) + [n + 1]
        
        output,j = [],0
        while j < k:
            # add current combination
            output.append(nums[:k])
            # increase first nums[j] by one
            # if nums[j] + 1 != nums[j + 1]
            j = 0
            while j < k and nums[j + 1] == nums[j] + 1:
                nums[j] = j + 1
                j += 1
            nums[j] += 1
            
        return output

具有回溯功能:

class Solution:
    def combine(self,k: int) -> List[List[int]]:
        def backtrack(first = 1,curr = []):
            # if the combination is done
            if len(curr) == k:  
                output.append(curr[:])
            for i in range(first,n + 1):
                # add i into the current combination
                curr.append(i)
                # use next integers to complete the combination
                backtrack(i + 1,curr)
                # backtrack
                curr.pop()
        
        output = []
        backtrack()
        return output

参考文献

  • 有关其他详细信息,请参见Discussion Board,您可以在其中找到很多公认的解决方案,其中包括有效的算法和渐近languages / { {3}}复杂度分析timespace
,

如果您在Solution类中声明函数,那么只有在您不想这样做时才必须将它们引用为self.dfs(...),然后在{{1 }}类。像这样:

Solution

而且,在Python中,它不是“推送”列表,而是“追加”,因此请将def dfs(...): # your body class Solution(..): def combine(...): 替换为temp.push