簡體   English   中英

帶有leetcode的全局變量python

[英]Global variable python with leetcode

我目前正在處理 Leetcode 中的爬樓梯問題,我的解決方案是使用遞歸。 要在不重置的情況下返回計數器,我必須使用全局計數。 這是我的代碼:

count =0
class Solution:
    def climbStairs(self, n: int) -> int:
        global count
        root = Tree()
        root.data = n
        if root.data - 1 >= 0:       
            root.left= self.climbStairs(n-1)
        if root.data -2 >= 0:     
            root.right= self.climbStairs(n-2)
        if (root.left == None) and (root.right == None):
            count+= 1
        return count

在單次運行中,每個案例看起來都不錯,但是當我提交它時,結果證明是錯誤的,我意識到是因為全局計數不會重置為每個測試案例(輸入 = 2 -> 輸出 =2,輸入 = 3 - > output =5 (應該是output = 3但是得到5因為(2 from the previous test case + 3 from the current test case).既然leetcode不讓我改變函數參數,反正我可以處理這個問題。 非常感謝

我想說的是,如果您針對一系列測試用例輸入 1、2、3、4、5、6 等運行您的解決方案,您將識別輸出產生的模式/序列,並找出更簡單的方法。 但是,如果你想按照你正在做的方式來做,一種方法是使用一個實例變量來跟蹤計數,以及一個實際執行遞歸的輔助函數,用於調用 expandStairs 函數, 例如:

class Solution:
    def count_ways(self, n):
        root = Tree()
        root.data = n
        if root.data - 1 >= 0:
            root.left = self.count_ways(n - 1)
        if root.data - 2 >= 0:
            root.right = self.count_ways(n - 2)
        if (root.left == None) and (root.right == None):
            self.count += 1
        return self.count

    def climbStairs(self, n):
        self.count = 0
        self.count_ways(n)
        return self.count

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM