leetcode--22. 括弧產生

來源:互聯網
上載者:User

有一段時間沒寫了,再進leetcode發現有了中國區的網站。

題目:22. 括弧產生

連結:https://leetcode-cn.com/problems/generate-parentheses/description/

給定正整數N,要求輸出N對括弧的所有合法組合。之前總是把一對括弧一起考慮,及在N-1對括弧的基礎上增加一對,於是當N=4的時候少了這種情況 (())(()),後面的遞迴結果自然就少了一些。下面是別人的思路:

左括弧和右括弧分開考慮,其個數分別用left和right表示(注意起頭第一個一定是左括弧)。當左括弧的個數left<N時,添加一個左括弧,此時若右括弧的個數right小於left,則可以添加一個右括弧。當left>=N時,只能添加右括弧。遞迴終止條件為left+right==2*N,此時將該組合加入結果集。

Python代碼:

class Solution(object):    def generateParenthesis(self, n):        """        :type n: int        :rtype: List[str]        """        # def getans(n, res, ans):        #     if n == 0:        #         if res not in ans:        #             ans.add(res)        #             return        #     else:        #         getans(n - 1, res + "()", ans)        #         getans(n - 1, "()" + res, ans)        #         getans(n - 1, "(" + res + ")", ans)        #        # ans = set()        # getans(n, "", ans)        def getret(n, left, right, ret, ans):            if left + right == n * 2:                ans.add(ret)                return            if left < n:                getret(n, left + 1, right, ret + "(", ans)                if right < left:                    getret(n, left, right + 1, ret + ")", ans)            else:                getret(n, left, right + 1, ret + ")", ans)        ans = set()        getret(n,0,0,"",ans)        return list(ans)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.