--- tags: LeetCode,Top 100 Liked Questions --- # 22. Generate Parentheses https://leetcode.com/problems/generate-parentheses/submissions/ ## 題目敘述 Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. ## Example Example 1: ``` Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] ``` Example 2: ``` Input: n = 1 Output: ["()"] ``` ## 解題想法 ### 1.backtracking base case:current length=max*2 and 左括號數量=右括號數量 且每次放進current的可以是左括號或右括號(左括號數量<max and 左括號數量>右括號數量) ``` class Solution { public: void backtracking(vector<string> &res,string current,int open,int close,int max){ //&res要記得傳位址才能改變res if(current.length()==max*2){/base case res.push_back(current); return; } if(open<max){//左括號數量<max current+="("; backtracking(res,current,open+1,close,max); current.pop_back();//要把加上的括號去掉 } if(close<open){//左括號數量<max and 左括號數量>右括號數量 current+=")"; backtracking(res,current,open,close+1,max); current.pop_back();//要把加上的括號去掉 } } vector<string> generateParenthesis(int n) { vector<string> res; backtracking(res,"",0,0,n); return res; } }; ``` 時間複雜度為O(N^2)