DFS全排列(正解和next_permutation函数取巧)

题目:

在这里插入图片描述

题目大意:

输入一个整数表示输入的测试样例
对于每一个样例输入一串字符,对其中的每一个字符进行全排列并输出
需要注意的是大写字母在相应的小写字母之前。
所以正确的字母顺序是’a’<‘a’<‘b’<‘B’<…<‘z’<‘Z’。

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <set>
#include<cstring>
using namespace std;
bool vis[15];
char res[15];
struct Anagram{
 int num;
 char ch;
}gram[15];
int len;
bool cmp(Anagram a, Anagram b) {
 return a.num < b.num; //排序
}
void dfs(int s) {
 if (s == len) {
  res[len] = '\0';
  printf("%s\n", res); //打印结果
  return;
 }
 char c = '.';    //c为标记是否遇见重复字母,例如aabd,则应该直接跳过第二个a
 for (int i = 0; i < len; i++) {
  if (!vis[i] && c != gram[i].ch) {
   vis[i] = true; //标记
   c = gram[i].ch;
   res[s] = gram[i].ch;
   dfs(s + 1);
   vis[i] = false; //回溯
  }
 }
}
int main() {
 int n;
 char words[15];
 while (scanf("%d", &n) != EOF) {
  while (n--) {
   memset(vis, false, sizeof(vis));
   scanf("%s", words);
   len = strlen(words);
   for (int i = 0; i < len; i++) {
    gram[i].ch = words[i];
    if (words[i] >= 'a' && words[i] <= 'z') { //AaBb 0123编号排序
     gram[i].num = (words[i] - 'a') * 2 + 1;
    }
    else if (words[i] >= 'A' && words[i] <= 'Z') {
     gram[i].num = (words[i] - 'A') * 2;
    }
   }
   sort(gram, gram + len, cmp); //排序,编号从小到大
   dfs(0);
  }
 }
}

当然这个题目也可以用next_permutation函数进行解答:

#include <algorithm>
#include<iostream>
#include<string.h>
using namespace std;
char a[20];
bool cmp(const char &a,const char &b)
{
    if(tolower(a)==tolower(b))
        return a<b;
    else
        return tolower(a)<tolower(b);
}
int main()
{
    int n;
    int t;
    cin>>n;
    while(n--)
    {
        cin>>a;
        t=strlen(a);
        sort(a,a+t,cmp);
        cout<<a<<endl;
        while(next_permutation(a,a+t,cmp))
        {
            cout<<a<<endl;
        }
    }
    return 0;
}

当然:

这相当与是取巧了。
这里用到了next_permutation函数
next_permutation函数具体用法
以及tolower函数(把字母字符转换成小写,非字母字符不做出处理)
tolower函数具体用法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值