ACwing92 递归实现指数型枚举 dfs

网址:https://www.acwing.com/problem/content/94/

题解:

每一层标记一个起点和下一层选择起点后的哪个数,选够数量或者超出$n$就返回,然后选数的数量枚举$1$至$n$即可。

AC代码:

#include <bits/stdc++.h>
using namespace std;
int sta[20], cnt;
int n;
void dfs(int beg, int div, int lim)
{
	if (div == lim)
	{
		for (int i = 0; i < lim; ++i)
		{
			printf("%d", sta[i]);
			if (i < lim - 1)
				printf(" ");
		}
		printf("\n");
		return;
	}
	for (int i = beg; i <= n; ++i)
	{
		sta[cnt++] = i;
		dfs(i + 1, div + 1, lim);
		--cnt;
	}
	return;
}
int main()
{
	scanf("%d", &n);
	for (int i = 0; i <= n; ++i)
		dfs(1, 0, i);
	return 0;
}

  

ACwing92 递归实现指数型枚举 dfs

上一篇:04.Delphi通过接口IInterface实现多重继承


下一篇:Acwing-120-防线(二分,前缀和)