Python Leetcode#77组合-不确定此语法有何错误

Python Leetcode#77组合-不确定此语法有何错误,python,attributes,Python,Attributes,我正在尝试学习python,并且正在解决leetcode问题,以便更加熟悉语法。我得到一个错误: NameError: name 'dfs' is not defined dfs(result, temp, 0, n, k) 我也不确定是否正确声明了列表,或者是否应该将self作为参数传递给函数 class Solution: def dfs(self, result: List[List[int]], temp:List[int], index: int, n: int, k

我正在尝试学习python,并且正在解决leetcode问题,以便更加熟悉语法。我得到一个错误:

NameError: name 'dfs' is not defined
    dfs(result, temp, 0, 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, temp, i, n, k)
                temp.pop()
                
    def combine(self, n: int, k: int) -> List[List[int]]:
        result = [[]];
        temp = [];
        dfs(result, temp, 0, n, k)
        return result

它应该是
self.dfs(结果、温度、0、n、k)
。因此,在本例中,
dfs
Solution
上的一种方法,因此当从
Solution
上的其他方法使用它时,您希望调用
self.dfs
,而不是
dfs
。或者,您可以将
dfs
的定义移到类之外,如下所示:

def dfs(...):
   ...

class Solution:
   ...

我假设这些是类上的方法的原因与leetcode接口的格式有关,它需要使用类而不是独立函数,但在Python中,
dfs
在大多数情况下是独立函数而不是方法可能更为惯用。一般来说,如果某个对象不需要使用
self
参数,也不需要被某个只引用特定对象的对象调用,那么就不需要将其作为一种方法。

使用
itertools.compositions
来解决这些算法问题不是最好的主意,但以防您不知道,在这里,我们可以解决这个问题

这将通过:

class Solution:
    def combine(self, n, 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

工具书类
  • 有关更多详细信息,请参阅,您可以在其中找到大量解释良好的公认解决方案,包括各种有效算法和渐近/复杂性分析

如果您在
解决方案
类中声明函数,那么您必须将它们称为
self.dfs(…)
只有在您不想这样做的情况下,才能在
解决方案
类之外编写您的函数。大概是这样的:

def dfs(...):
    # your body

class Solution(..):
    def combine(...):

而且,在Python中,它不是列表的“推送”,而是“附加”,因此请将
temp.push
替换为
temp.append

是的,这似乎是Leetcode的一个怪癖。让
dfs
成为
staticmethod
可能更为惯用,但理想情况下,它应该是一个独立的函数。您的语法很好,问题在于如何引用函数。顺便说一句,去掉分号;他们什么也不做。
def dfs(...):
    # your body

class Solution(..):
    def combine(...):