题解 非递归实现组合型枚举

题目链接

用栈模拟dfs即可

#include<cstdio>
#include<stack>
using namespace std;
struct state {
	int pos,num,a;//第pos位,当前已有num个数字,用二进制状态压缩进a(省去数组存储)
};
stack<state> s;
int n,m;
int main() {
	scanf("%d%d",&n,&m);
	s.push((state) {
		0,0,0
	});
	while(!s.empty()) {
		state a=s.top();
		s.pop();
		if (a.num+n-a.pos<m) continue;
		if (a.num==m) {
			for (int i=0; i<n; i++)
				if ((a.a>>i)&1) printf("%d ",i+1);
			puts("");
			continue;
		}
		if (a.pos<n) {
			s.push((state) {
				a.pos+1,a.num,a.a
			});
			s.push((state) {
				a.pos+1,a.num+1,a.a|(1<<a.pos)
			});//题目是从小到大输出,所以小的要放在后面,先从栈中取出。这与dfs不太一样
		}
	}
}
posted @ 2019-12-28 19:12  Randolph、  阅读(266)  评论(0编辑  收藏  举报