leetcode-22.Generate Parentheses 括號生成
阿新 • • 發佈:2018-12-22
題目:
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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] |
給出 n 代表生成括號的對數,請你寫出一個函式,使其能夠生成所有可能的並且有效的 例如,給出 n = 3,生成結果為: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] |
思路:DFS. 對這種列出所有結果的題目,都可以考慮用遞迴來解。這裡字串只有左括號和右括號兩種,每種3個,我們令left=3為左括號個數,right=3為右括號個數。擋在某次遞迴時出現left>right,則直接返回,若出現left==right==0,就說明左右 括號都列印完了。否則,先列印左括號,left--,再列印右括號,right--.
class Solution { public: vector<string> generateParenthesis(int n) { vector<string> res; dfs(n,n,"",res); return res; } void dfs(int left,int right,string out,vector<string> &res) { if(left > right) return; if(left==0 && right == 0) res.push_back(out); else { if(left>0) dfs(left-1,right,out+"(",res); if(right>0) dfs(left,right-1,out+")",res); } }