# 22 Generate Parentheses

給一正整數n,表示n組括號(包含左右),回傳List包含所有可能的、合法的括號排列組合。 example

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

idea
build string recursively, each time add either a '(' or ')' 終止條件:

  1. 若左或右括號已用超過n個,則不合法。
  2. 若使用的右括號數量大於左括號,則不合法。
  3. 若左右括號數量都用光,則存入List

總結起來可以得到以下pseudocode

pseudocode

main():
call helper function

helper(str, numOfLeft, numOfRight, n, res):
  if(numOfLeft < 0 || numOfRight < 0)//number used
    return;

  if(numOfLeft == 0 && numOfRight == 0)
    add str to res  

  if(numOfRight < numOfLeft){
    helper(str+"(", numOfLeft-1, numOfRight, n, res)
    helper(str+")", numOfLeft, numOfRight, n, res)
  }

  return;

Code

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        int numOfRight = n;
        if(n < 1) return res;
        helper("(", n-1, numOfRight, res, n);
        return res;
    }

    private void helper(String str, int numOfLeft, int numOfRight, List<String> res, int n){
        if(numOfLeft < 0 || numOfRight < 0)
            return;

        if(numOfLeft == 0 && numOfRight == 0)
            res.add(str);

        if( numOfRight >= numOfLeft){
            helper(str + "(", numOfLeft-1, numOfRight, res, n);
            helper(str + ")", numOfLeft, numOfRight-1, res, n);
        }

        return;
    }
}

results matching ""

    No results matching ""