1. 程式人生 > >【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題4:Generate Parentheses

【LeetCode & 劍指offer刷題】回溯法與暴力列舉法題4:Generate Parentheses

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

Generate Parentheses

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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
C++   //問題:產生括號對
//方法一:回溯法(並沒有回溯,應該就叫普通遞迴法) /* 遞迴,並用兩個變數(open, close)記錄當前左括號和右括號的個數  open < n (n為括號對數量)時新增左括號,close<open時新增右括號 Once we add a '(' we will then discard it and try a ')' which can only close a valid '('. Each of these steps are recursively called
舉例:(n=3時的遞迴樹)                                 --> (((,3,0,3--> (((),3,1,3--> ((()),3,2,3--> ((())),3,3,3 return                     --> ((,2,0,3                                               --> (()(, 3,1,3--> (()(), 3,2,3--> (()()), 3,3,3 return "",0,0,3 --> (,1,0,3            --> ((), 2,1,3                                               --> (()), 2,2,3--> (())(, 3,2,3--> (())(), 3,3,3 return                                                                   --> ()((,3,1,3--> ()((),3,2,3--> ()(()),3,3,3 return                     --> (),1,1,3--> ()(, 2,1,3                                               --> ()(),2,2,3--> ()()(,3,2,3--> ()()(),3,3,3 return                                 */ class Solution { public :     vector < string > generateParenthesis ( int n )     {         vector < string > ans ;         recursion ( ans , "" , 0 , 0 , n );         return ans ;     }     private :     void recursion ( vector < string >& ans , string s , int open , int close , int n )     {         if ( s . length () == 2 * n )         {             ans . push_back ( s );             return ;         }                 //深度優先搜尋,分支為加左括號和右括號,深度方向左括號和右括號保證匹配         if(open < n) recursion ( ans , s+'(', open+1 , close , n ); //遞迴樹有很多分支,遍歷到所有可能的情況          if(close < open) recursion ( ans , s+')' , open , close+1 , n ); //加右括號,直到左右括號相匹配     } };