题目链接:https://www.acwing.com/problem/content/description/94/
题目要求输出所有组合,这里使用DFS来解决,凡是涉及递归的,都可以画搜索树来辅助。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
bool f[20];
void dfs(int u)
{
if (u > n) {
for (int i = 0; i <= n; i++) {
if (f[i])
cout << i << " ";
}
cout << endl;
return;
}
f[u] = true;
dfs(u + 1);
f[u] = false;
dfs(u + 1);
}
int main()
{
cin >> n;
dfs(1);
return 0;
}