leetcode 22 Generate Parentheses

題目詳情

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

輸入一個正整數n。要求返回一個List<String>,list中包含n組括號全部可能的符合規則的組合。如「(())」就屬於符合規則的組合,「)(()」就屬於不符合規則的組合。code

例如, 輸入 n = 3, 結果集應當是:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]orm

想法

  • 輸入的n就表明着咱們的字符串的組成是n個"("和n個")"。
  • 聲明一個cur字符串來暫存咱們沒次操做得到的字符串,而咱們每次想要將括號加入cur字符串的時候,咱們要保證剩餘的括號和現有字符串,能夠知足規則。也就是說,若是咱們想加入一個")",咱們要保證cur字符串中的")"的數量小於"("的數量,不然字符串就不符合規則了。
  • 咱們須要跟蹤"("和")"的使用狀況,來判斷下一步的操做是否合法。

解法

public List<String> generateParenthesis(int n) {
            List<String> ans = new ArrayList();
            backtrack(ans, "", 0, 0, n);
            return ans;
        }

        public void backtrack(List<String> ans, String cur, int open, int close, int max){
            if (cur.length() == max * 2) {
                ans.add(cur);
                System.out.println(cur);
                return;
            }

            if (open < max)
                backtrack(ans, cur+"(", open+1, close, max);
            if (close < open)
                backtrack(ans, cur+")", open, close+1, max);
        }
相關文章
相關標籤/搜索