先贴个代码:
以及原题链接: 3429. 全排列 - AcWing题库https://www.acwing.com/problem/content/description/3432/
这题也是很简单的全排列,主要变成了字符串会有点麻烦,这里说明输出要求按字典序从小到大,题目中告诉我们输入时保证字典序顺序,所以这题会简单点,但我一开始没看到(bushi)所以还复杂的写了个string类型的数组,但问题不大,就当写了道更难的题,这里说明一下,如果题目中的输入没有按照字典序从小到大给出,我们需要手动存答案排序,那样就会用到string自带的比较运算符重载和sort函数来解决这一问题。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 10;
bool st[N];
char list[N], len = 0;
char tmp[N];
string ans[1000];
int cnt = 0;
void dfs(int x)
{
if (x == len)
{
for (int i = 0; i < len; ++i)
{
ans[cnt] += tmp[i];
}
cnt++;
return;
}
for (int i = 0; i < len; ++i)
{
if (!st[i])
{
st[i] = true;
tmp[x] = list[i];
dfs(x + 1);
st[i] = false;
}
}
}
int main()
{
char c;
while (cin >> c)
{
list[len++] = c;
}
dfs(0);
for (int i = 0; i < cnt; ++i)
cout << ans[i] << endl;
}
顺带一提,做简单题就是爽,被数论搞混迷了做了几道简单的dfs感觉又复活了。
by————2024.4.11刷题记录