2013.12.7 00:49
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Solution:
If you're familiar with the Catalan Numbers, you'll see it's a typical solution for this problem.
Since all the combinations are required, we'll use DFS to go through every possible sequence.
Let's consider the recursion in the following way:
1. For a sequence of length 2 * n, there're n '(' and n ')'
2. For a valid sequence, number of '(' will never be less than the number of ')' at any position. If there're more ')' than '(', there must be a mismatch.
3. Always do the recursion from left to right.
Time complexity is H(n) * O(n) = C(2 * n, n) / (n + 1) * n, that's roughly O(n!). Space complexity is not sure yet...
Accepted code:
1 // 1AC, simple recursion will do, but keep your mind clear or it's easy to get things complicated 2 class Solution { 3 public: 4 vector<string> generateParenthesis(int n) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 result.clear(); 8 9 dfs(n, n, ""); 10 11 return result; 12 } 13 private: 14 vector<string> result; 15 16 void dfs(int cl, int cr, string pat) { 17 if(cl == 0 && cr == 0){ 18 result.push_back(pat); 19 } 20 21 int i; 22 if(cl < cr){ 23 if(cl > 0){ 24 dfs(cl - 1, cr, pat + "("); 25 } 26 if(cr > 0){ 27 dfs(cl, cr - 1, pat + ")"); 28 } 29 }else if(cl == cr){ 30 if(cl > 0){ 31 dfs(cl - 1, cr, pat + "("); 32 } 33 }else{ 34 return; 35 } 36 } 37 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)