n个数,入栈出栈,所有情况

int count = 0;
void print(vector<int>& trace, vector<int>& push_order) {
	int i = 0;
	stack<int>stk;
	for (auto n : trace) {
		if (n == 1) {
			stk.push(push_order[i++]);
		}
		else {
			int num = stk.top();
			stk.pop();
			cout << num << " ";
		}
	}
	cout << endl;
	::count++;
}

void backtrack(vector<int>& trace, vector<int>& push_order, int left) { // trace:{0 出栈,1 入栈}, push_order:操作的数字, left:push比pop多的次数,也就是栈中还有几个数
	//    left记录前缀序列中1的个数,每当trace中push一个0,就减一
	if (trace.size() == 2 * push_order.size()) { // 递归出口
		if (left == 0) // 只有left=0,才能使得0的数量==1的数量,才是合法的。
			print(trace, push_order);
		return;
	}
	// 做选择
	if (left > 0) { // 如果left>0,则可以push 0进去 ,同时 left-1
		trace.push_back(0);
		backtrack(trace, push_order, left - 1);
		// 撤销选择
		trace.pop_back();
	}
	trace.push_back(1);
	backtrack(trace, push_order, left + 1);
	trace.pop_back();
}
int main() {
	vector<int> push_order = { 1,2,3,4 };
	vector<int>trace;
	backtrack(trace, push_order, 0);
	cout << ::count << endl;

	const int maxI = 4;
	function<void(stack<int>&, list<int>&, int)> fun = [&](stack<int> st, list<int> out, int index) {
		if (out.size() == maxI) {
			for_each(begin(out), end(out), [](int x) {cout << x << " "; }), cout << endl;
			return;
		}
		if (st.size() > 0) {
			int t = st.top();	st.pop();	out.push_back(t);
			fun(st, out, index);
			st.push(t);	out.pop_back();
		}
		if (index <= maxI) {
			st.push(index++);
			fun(st, out, index);
		}
	};
	stack<int>st;
	list<int> out;
	fun(st, out, 1);

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值