简体   繁体   English

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

[英]Leetcode #77 Combinations - Not sure what is wrong with this syntax

I am trying to learn python and am doing leetcode problems to become more familiar with the syntax.我正在尝试学习 python 并且正在做 leetcode 问题以更加熟悉语法。 I am getting the error:我收到错误消息:

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

I am also not sure if I am declaring the lists correctly or if I should pass self as a parameter to the functions.我也不确定我是否正确声明了列表,或者我是否应该将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

It should be self.dfs(result, temp, 0, n, k) .它应该是self.dfs(result, temp, 0, n, k) So change to self.dfs wherever you are using dfs所以无论你在哪里使用dfsself.dfs

In this example, dfs is a method on Solution , so when using it from other methods on Solution you want to call self.dfs instead of dfs .在此示例中, dfsSolution上的一个方法,因此当从Solution上的其他方法使用它时,您需要调用self.dfs而不是dfs Alternatively, you could move the definition of dfs outside of the class, like so:或者,您可以将dfs的定义移到 class 之外,如下所示:

def dfs(...):
   ...

class Solution:
   ...

I assume that the reason these are methods on a class is something about the format of leetcode's interface that requires the use of classes rather than free-standing functions, but probably it would be more idiomatic in Python for dfs to be a free-standing function rather than a method in most cases. I assume that the reason these are methods on a class is something about the format of leetcode's interface that requires the use of classes rather than free-standing functions, but probably it would be more idiomatic in Python for dfs to be a free-standing function而不是大多数情况下的方法。 Generally if something doesn't need to use the self argument and doesn't need to be called by something that only has a reference to a specific object, there's no need to make it a method.通常,如果某些东西不需要使用self参数并且不需要被仅引用特定 object 的东西调用,则无需将其设为方法。

It's not the best idea to use itertools.combinations for solving these algorithm problems, but just in case you didn't know, here we can solve the problem with that.使用itertools.combinations解决这些算法问题并不是最好的主意,但以防万一你不知道,我们可以用它来解决问题。

This'll pass:这将通过:

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

Here are some of LeetCode's solutions with comments, implementing the same idea:以下是 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

With backtracking:带回溯:

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

References参考

  • For additional details, please see the Discussion Board which you can find plenty of well-explained accepted solutions in there, with a variety of languages including efficient algorithms and asymptotic time / space complexity analysis 1 , 2 .有关更多详细信息,请参阅讨论板,您可以在其中找到大量解释清楚且公认的解决方案,包括多种语言,包括高效算法和渐近时间/空间复杂度分析12

If you declare the functions inside the Solution class, then you have to refer to them as self.dfs(...) only if you don't want to do that, then write your function outside the Solution class.如果您在Solution class 中声明函数,那么只有在您不想这样做时才必须将它们称为self.dfs(...) ,然后在Solution ZA2F2ED4F8EBC2CBB4C21A29DZ40 之外编写您的 function。 Something like this:像这样的东西:

def dfs(...):
    # your body

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

And also, in Python, it is not 'push' for lists it is 'append' so please replace temp.push to temp.append此外,在 Python 中,它不是“推送”列表,它是“附加”,所以请将temp.push替换为temp.append

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM