平衡括号问题

相关问题:http://blog.csdn.net/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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值