leetcode系列(44)Generate Parentheses
来源:互联网 发布:mac mobi转pdf软件 编辑:程序博客网 时间:2024/04/30 08:26
Given n pairs ofparentheses, write a function to generate all combinations of well-formedparentheses.
For example, given n = 3,a solution set is:
"((()))", "(()())","(())()", "()(())", "()()()"
解答:这个题目用递归的方式可以比较方便的解决,假如有n个'('和')',ret里面放入当前valid的括号们(初始为空),加入已经放了若干个'('和')'到ret中,剩下rest_left个'('和rest_right个')',当rest_left>0时直接放'('到ret中都会满足valid parentheses,但是只有rest_right>rest_left的时候才能放')',因为rest_right < rest_left肯定是invalid,rest_right == rest_left时,放')'到ret中也会造成rest_right < rest_left从而invalid。
class Solution {public: vector<string> generateParenthesis(int n) { vector<string> ret; string cur; generateHelper(ret, n, n, cur); return ret; } private: void generateHelper(vector<string>& ret, int rest_left, int rest_right, const string& cur) { if (rest_left == 0 && rest_right == 0) { ret.push_back(cur); } if (rest_left > 0) { generateHelper(ret, rest_left - 1, rest_right, cur + '('); } if (rest_right > rest_left) { generateHelper(ret, rest_left, rest_right - 1, cur + ')'); } }};
0 0
- leetcode系列(44)Generate Parentheses
- 【Leetcode长征系列】Generate Parentheses
- [leetcode刷题系列]Generate Parentheses
- LeetCode(22)Generate Parentheses
- 《leetCode》:Generate Parentheses(hard)
- (Leetcode)22. Generate Parentheses
- LeetCode (22)Generate Parentheses
- Leetcode-Generate Parentheses(递归)
- 《leetCode》:Generate Parentheses(hard)
- LeetCode | Generate Parentheses(生成括号)
- LeetCode之Generate Parentheses(C++)
- LeetCode 22 Generate Parentheses(生成括号)
- LeetCode 22. Generate Parentheses(生成括号)
- LeetCode进阶之路(Generate Parentheses)
- LeetCode 22 Generate Parentheses(生成括号)
- leetcode 22. Generate Parentheses (暴力递归)
- 【LeetCode算法练习(C++)】Generate Parentheses
- LeetCode: Generate Parentheses
- 【基础练习】【DFS】codevs2806 红与黑题解
- **LeetCode-Inorder Successor in BST
- 【基础练习】【DFS】codevs2549 自然数和分解题解
- Online random forest
- 如何从上位机或者触摸屏设定Time或S5Time值?
- leetcode系列(44)Generate Parentheses
- iOS --- 音量调节视图MPVolumeView的使用
- JSON对象长度和遍历方法-前端开发博客
- App 快速上架经验
- 按位与运算符
- 关于ExecuteNonQuery()执行成功却返回-1的问题
- 微服务年度总结,看完这个你应该知道如何回答别人的问题了。
- mysql 不能插入中文和显示中文
- 3D打印