# 22. Generate Parentheses

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LM2SVqXJzbyasbVJlPA%2F-LM2axgurWc3OE1X8ADN%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-09-10%20%E4%B8%8B%E5%8D%889.10.38.png?alt=media\&token=9158f9a9-6587-43cd-b663-39230374e5c9)

## 2.想法

* 提問
* function header, parameter
* test input
* 說明想法
  * 可以看成"(", ")"的排列組合, 使用ray tracking, 並限制長度個數 (用減的)
  * 但是"("一定要出現在")"之前, 否則return
* 測試計算複雜度: O(2 ^ n)

## **3.程式碼**

```
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        generate(n, n, "", res);
        return res;
    }
private:
    void generate(int left, int right, string out, vector<string>& res) {
        if (left < right) {
            return;
        }
        if (left == 0 && right == 0){
            res.push_back(out);
            return;
        }
        if (left > 0) {
            generate(left - 1, right, "(" + out, res);
        }
        if (right > 0) {
            generate(left, right - 1, ")" + out, res);
        }
    }
};
```
