摘要:復(fù)雜度思路注意的地方,要限制左括號和右括號。每出現(xiàn)一次左括號,就相對于限定了,最多只能出現(xiàn)那么多右括號。所以,為了完成這種限定,用來控制。不然會(huì)有的情況出現(xiàn)。
LeetCode[22] Generate Parentheses
BackTrackingGiven n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
復(fù)雜度
O(N!),O(N)
思路
注意trick的地方,要限制左括號和右括號。每出現(xiàn)一次左括號,就相對于限定了,最多只能出現(xiàn)那么多右括號。所以,為了完成這種限定,用right - 1來控制。不然會(huì)有“(()))(”的情況出現(xiàn)。
代碼
public ListgenerateParenthesis(int n) { List res = new LinkedList<>(); helper(res, 0, n, n, new StringBuilder()); return res; } public void helper(List res, int left, int right, int n, StringBuilder temp) { // Base case; if(left == n && right == n) { res.add(temp.roString()); } if(left < n) { // 限制在當(dāng)前這么多左括號的情況下,最多只能出現(xiàn)那么多的右括號。 helper(res, left + 1, right - 1, n, temp.append("(")); temp.deleteCharAt(temp.length() - 1); } if(right < n) { helper(res, left, right + 1, n, temp.append(")")); temp.deleteCharAt(temp.length() - 1); } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65249.html
Problem Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ ((())), (()()), (())(), ()(()), ...
摘要:當(dāng)右括號和左括號的剩余量均為時(shí),及為一個(gè)最終結(jié)果。而則會(huì)在直接原來的對象上進(jìn)行修改,其指針仍然指向原來的對象。因此在遞歸的過程中使用一定要注意,對對象的修改不要相互干擾。 題目要求 Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses....
摘要:要求返回一個(gè)中包含組括號所有可能的符合規(guī)則的組合。例如輸入結(jié)果集應(yīng)當(dāng)是想法輸入的就代表著我們的字符串的組成是個(gè)和個(gè)。我們需要跟蹤和的使用情況,來判斷下一步的操作是否合法。 題目詳情 Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses....
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時(shí)也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個(gè)索引嘻嘻。 順序整理 1~50 1...
摘要:構(gòu)造個(gè)成對括號給出一個(gè)整數(shù),實(shí)現(xiàn)一個(gè)函數(shù)生成對小括號,對小括號的左右括弧順序不限,但應(yīng)該閉合。思路的情況為時(shí)的括號串中在縫隙位置再插入一個(gè)括號,如中位置。遞歸解決,時(shí)為在和中再插入一個(gè)括號。 構(gòu)造n個(gè)成對括號 Generate Parentheses 給出一個(gè)整數(shù)n,實(shí)現(xiàn)一個(gè)函數(shù)生成n對小括號,n對小括號的左右括弧順序不限,但應(yīng)該閉合。 Given n pairs of parent...
閱讀 1525·2021-08-09 13:47
閱讀 2783·2019-08-30 15:55
閱讀 3509·2019-08-29 15:42
閱讀 1128·2019-08-29 13:45
閱讀 3022·2019-08-29 12:33
閱讀 1755·2019-08-26 11:58
閱讀 997·2019-08-26 10:19
閱讀 2425·2019-08-23 18:00