相关问题:http://blog.youkuaiyun.com/flowerdasiy/article/details/39202215 (高矮人站队问题)
括号平衡问题,例如 ((()()))是平衡的,但是)()是不平衡的。
问题,一共有n个左括号和n个右括号,请找出所有的括号平衡序列。
思路一:
Recursion. Base case is which the solution has size of 2*n. Recursive step: each time we count number of open parenthesis and closed parenthesis. If open == closed, then we have to add open parenthesis. If open > closed, we can add open parenthesis as long as we do not exceed n. We can also add closed parenthesis.
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> solutions;
string solution;
recursion(n, solution, solutions);
return solutions;
}
void recursion(int n, string solution, vector<string> &solutions) {
if(solution.size() == 2*n) {
solutions.push_back(solution);
} else {
int left = 0;
int right = 0;
for(int i = 0; i < solution.size(); ++i) {
if(solution[i] == '(')
left++;
if(solution[i] == ')')
right++;
}
if(left == right)
recursion(n, solution + "(", solutions);
else if(left > right) {
if(left < n)
recursion(n, solution + "(", solutions);
recursion(n, solution + ")", solutions);
}
}
}
};
思路二:
代码:
#include <iostream>
#include <stack>
using namespace std;
static int count = 0; // counting the total number of valid cases
void balancing_parenthesis(int open, int close, stack<char> st)
// open: the remaining number of open parentheses
// close: the remaining number of close parentheses
// At anytime, close is greater than or equal to open
{
if(open == 0)
{
for(int i=0;i<close;i++)
st.push('c');
int _num = st.size();
for(unsigned int i=0; i<_num; i++)
{
cout<<st.size()<<st.top()<<" ";
st.pop();
}
cout<<endl;
count++;
return;
}
if(open == close)
{
st.push('o');
balancing_parenthesis(open-1, close, st);
}
else
{
st.push('o');
balancing_parenthesis(open-1, close, st);
st.pop();
st.push('c');
balancing_parenthesis(open, close-1, st);
}
}
int main()
{
stack<char> st;
balancing_parenthesis(5,5,st);
cout<<endl<<count<<endl;
int x;
cin>>x;
}