目录
123的全排列
如下图,使用递归树展现,枚举位置。
具体代码:
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 100
int a[N];
int n,m;
int mem[N];
bool st[N];
void dfs(int x) //x是当前位置
{
if(x > 2)
{
for(int i = 0; i < 3; i ++)
{
cout<<a[i];
}
cout<<endl;
return ;
}
for(int i = 1; i <= 3; i ++)
{
if(!st[i])
{
a[x] = i;
st[i] = true; // 标记为使用过
dfs(x + 1); //深搜
st[i] = false; // 回溯,撤销处理结果
}
}
}
int main()
{
dfs(0);
return 0;
}
相关例题:
全排列
P1706 全排列问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
带分数
例如:
用户输入:
100
程序输出:
11
再例如:
用户输入:
105
程序输出:
6
思路详解
1.枚举1-9的全排列
2.将全排类分割成a b c
3.判断该枚举的数组成的a b c,是否可以使等式成立
成立的话,res++;
带分数代码实现
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 100
int a[N];
int n,m;
int mem[N];
int st[N];
int res;
int calculate(int l, int r) //计算a b c
{
int res = 0;
for(int i = l; i <= r; i++)
{
res = res * 10 + a[i];
}
return res;
}
void dfs(int x)
{
if(x > 8)
{
for(int i = 0; i < 9 - 2; i ++)
{
for(int j = i + 1; j < 9 - 1; j++)
{
int a = calculate(0, i);
int b = calculate(i + 1, j);
int c = calculate(j + 1, 8);
//if( n == a + b / c)
if( n * c == (a * c + b))
res++;
}
}
return ;
}
for(int i = 1; i <= 9; i ++)
{
if(!st[i])
{
a[x] = i;
st[i] = true;
dfs(x + 1);
st[i] = false;
}
}
}
/*思路
1.枚举1-9的全排列
2.将全排类分割成a b c
3.判断该枚举的数组成的a b c,是否可以使等式成立
成立的话,res++;
*/
int main()
{
scanf("%d",&n);
dfs(0);
printf("%d",res);
return 0;
}
两道例题
全排列
P1706 全排列问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
带分数