知识点总结
递归:自己调用自己
2^15 = 32768
2^16 = 65536
字典序:从小到大枚举,能放就放
92. 递归实现指数型枚举
思路一:状态压缩写法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n;
void dfs(int u, int state)
{
if (u == n)
{
for (int i = 0; i < n; i ++ )
if (state >> i & 1)
printf("%d ", i + 1);
puts("");
return ;
}
dfs(u + 1, state);
dfs(u + 1, state | (1 << u));
}
int main()
{
scanf("%d", &n);
dfs(0, 0);
return 0;
}
常规写法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 18;
int n;
int st[N];
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i ++ )
if (st[i] == 1)
printf("%d ", i + 1);
puts("");
return ;
}
st[u] = 2;
dfs(u + 1);
st[u] = 0;
st[u] = 1;
dfs(u + 1);
st[u] = 0;
}
int main()
{
scanf("%d", &n);
dfs(0);
return 0;
}
94. 递归实现排列型枚举
思路一:
枚举每个数放到每个位置
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
int ans[N];
bool st[N];
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i ++ )
printf("%d ", ans[i]);
puts("");
return ;
}
for (int i = 1; i <= n; i ++ )
if (!st[i])
{
st[i] = true;
ans[u] = i;
dfs(u + 1);
st[i] = false;
ans[u] = 0;
}
}
int main()
{
scanf("%d", &n);
dfs(0);
return 0;
}
93. 递归实现组合型枚举
保证枚举的时候,升序排列
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30;
int n, m;
int ans[N];
void dfs(int u, int start)
{
if (u + n - start < m) return ;
if (u == m + 1)
{
for (int i = 1; i <= m; i ++ )
printf("%d ", ans[i]);
puts("");
return ;
}
for (int i = start; i <= n; i ++ )
{
ans[u] = i;
dfs(u + 1, i + 1);
ans[u] = 0;
}
}
int main()
{
scanf("%d%d", &n, &m);
dfs(1, 1);
return 0;
}
1209. 带分数
思路一:搜索
1~n枚举a和c,判断b是否满足要求,中间过程适当剪枝
边界问题:a、b、c必须是正数
b是否合法:b中每一位a和c都没有使用过,并且最后所有数字都被用完
剪枝:某一个数是0就剪枝,或者某一个数超过n,
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20;
int n, ans;
bool st[N], backup[N];
bool check(int a, int c)
{
int b = n * c - a * c;
if (!a || !b || !c) return false;
memcpy(backup, st, sizeof st);
while (b)
{
int x = b % 10;
b /= 10;
if (!x || backup[x]) return false;
backup[x] = true;
}
for (int i = 1; i <= 9; i ++ )
if (!backup[i])
return false;
return true;
}
void dfs_c(int u, int a, int c)
{
if (u == n) return ;
if (check(a, c)) ans ++ ;
for (int i = 1; i <= 9; i ++ )
if (!st[i])
{
st[i] = true;
dfs_c(u + 1, a, c * 10 + i);
st[i] = false;
}
}
void dfs_a(int u, int a)
{
if (a >= n) return ;
if (a) dfs_c(u + 1, a, 0);
for (int i = 1; i <= 9; i ++ )
if (!st[i])
{
st[i] = true;
dfs_a(u + 1, a * 10 + i);
st[i] = false;
}
}
int main()
{
scanf("%d", &n);
dfs_a(0, 0);
cout << ans << endl;
return 0;
}