22. Generate Parentheses
生活随笔
收集整理的這篇文章主要介紹了
22. Generate Parentheses
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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:
["((()))","(()())","(())()","()(())","()()()" ]解題思路:本題就是個(gè)遞歸。
當(dāng)左括號(hào)大于右括號(hào)的時(shí)候,可以選擇左或者右
當(dāng)左括號(hào)等于右括號(hào)的時(shí)候選擇右=左 class Solution { public:void helper(vector<string>&res, int sum, int left, int right,string str){if(left+right==sum){if(left==right){res.push_back(str);}return ;}if(left<right)return;helper(res,sum,left+1,right,str+"(");if(left>right){helper(res,sum,left,right+1,str+")");}}vector<string> generateParenthesis(int n) {vector<string>res;helper(res,2*n,0,0,"");return res;} };
?
轉(zhuǎn)載于:https://www.cnblogs.com/tsunami-lj/p/7600583.html
總結(jié)
以上是生活随笔為你收集整理的22. Generate Parentheses的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux/Windows系统如何安装P
- 下一篇: asp.net core的文件下载