• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Foreordination
酒后高歌磨剑,梦中快意恩仇,名利脚下踩,情义两肩挑
博客园    首页    新随笔    联系   管理    订阅  订阅
排列问题

排列问题:

开学了BOSS要求你写一个程序:输入一个包含n(n<10)个字符的字符串,按字典顺序输出这个n个字符的所有的排列,输入的字符串中有些字母可能出现多次,要求输出中不能有相同的排列。

例如:给你一个字符串abc,你需要输出这三个字母不同的组合:abc acb bac bca cab cba

★数据输入

 输入的第一行为数字 K(1<=K<=50),表示接下来的输入有 K 行。每一行包含一个字符 串。每个字符串都是由从 A到 Z的大写或小写字母组成,规定大写和小写字母是不相同的。 每个字符串的长度不大于 10。

★数据输出

 每个字符串的输出应该包含所有不同排序。同一个字符串对应的结果按字母顺序升序 输出。同一个字母的大写优先于小写输出。

/*方法一:使用STL实现*/
#include<cstdlib>
#include<string>
#include<iostream>
#incluude<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<ctime>
#include<cstdio>
#include<stack>
#include<map>
#include<queue>
#include<vector>

using namespace std;
bool compare(char a,char b)
{
    if(tolower(a)!=tolower(b))
    {
        return tolower(a)<tolower(b)
    }
    else
    {
        return a<b
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    char a[15];
    while(n--)
    {
        scanf("%s",a);
        int len=strlen(a);
        sort(a,a+len,compare);
        do
        {
            printf("%s\n",a);
        } while (next_permutation(a,a+len,compare));
    }
    return 0;
}
/*方法二:递归实现*/
#include<cstdlib>
#include<string>
#include<iostream>
#incluude<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<ctime>
#include<cstdio>
#include<stack>
#include<map>
#include<queue>
#include<vector>

using namespace std;

//区间反转
void Reverse(char *start,char *end)
{
    while(start<end)
    {
        swap(*start++,*end--);
    }
}

bool compare(char a,char b)
{
    if(tolower(a)!=tolower(b))
    {
        return tolower(a)<tolower(b);
    }
    else 
    {
        return a<b;
    }
}

bool hasNext(char a[])
{
    char *p,char *q,*replaceNum,*end;
    p=end=a+strlen(a)-1;
    while(p!=a)//p是替换点
    {
        q=p;
        p--;
        if(compare(*p,*q))//寻找替换数
        {
            replaceNum=end;
            while(compare(*replaceNum,*p)||*replaceNum==*p)
            {
                replaceNum--;
            }
            swap(*p,*replaceNum);
            Reverse(p+1,end);//逆转替换点后面的所有数
            return true;
        }
    }
    Reverse(a,end);
    return false;
}

int main()
{
    int n;
    char a[15];
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",a);
        int len=strlen(a);
        sort(a,a+len,compare);
        do
        {
            printf("%s\n",a)
        }while(hasNext(a));
    }
    return 0;
}

 

posted on 2018-03-25 18:53  Foreordination  阅读(236)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3