一、题目链接
二、题目分析
(一)算法标签
DFS 递归
(二)解题思路
DFS最重要的就是顺序
本题从前往后(1~n)依次考虑每个数选或者不选
详细了解搜索类题目(DFS、BFS),请移步DFS BFS 搜索题目归纳
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 16;
int n;
int st[N]; // 0 :未考虑 1: 不选 2 :选
void dfs(int u)
{
if (u > n)
{
for (int i = 1; i <= n; i++ )
if (st[i] == 2)
printf("%d ", i);
puts("");
return;
}
st[u] = 1;
dfs(u + 1);
st[u] = 0;
st[u] = 2;
dfs(u + 1);
st[u] = 0;
}
int main()
{
cin >> n;
dfs(1);
return 0;
}
用vector<vector>记录方案
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 16;
int n;
int st[N]; // 0 :未考虑 1: 不选 2 :选
// 记录方案 一共有2^N个方案,每个方案最多N个数,所以第一维是1 << N,第二维是N
vector<vector<int>> ways;
void dfs(int u)
{
if (u > n)
{
vector<int> way;
for (int i = 1; i <= n; i++ )
if (st[i] == 2)
way.push_back(i);
ways.push_back(way);
return;
}
st[u] = 1;
dfs(u + 1);
st[u] = 0;
st[u] = 2;
dfs(u + 1);
st[u] = 0;
}
int main()
{
cin >> n;
dfs(1);
for (int i = 0; i < ways.size(); i ++ )
{
for (int j = 0; j < ways[i].size(); j ++ )
printf("%d ", ways[i][j]);
puts("");
}
return 0;
}