UVA 10098 Generating Fast

本文探讨了如何使用C++实现字符串字典序全排列的算法,包括使用next_permutation()函数和自定义递归函数的方法。文章详细介绍了算法的实现过程、注意事项以及输出格式要求,特别强调了避免输出重复排列的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析

给一串,要求输出其字典序全排列。
相对需要注意的是,该串可能有重复数字,并且不应输出重复的排列。

这里可以在填充每一格的时候,检查一下当前已经填充的格子里和这格相同的有几个,判断有没有超过给定串里头的限定个数,如果没有可以填充。

另外不能重复,可以考虑使用这一格前,检查上一次使用的格是不是和这格内容一致,如果一致那么因为只考虑内容重复,会导致再输出一组重复排列。

当然,使用next_permutation()也是好方法。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
using std::next_permutation;
using std::sort;

char s[50];
int main()
{
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%s", s);
        sort(s, s+strlen(s));
        do {
            printf("%s\n", s);
        } while (next_permutation(s, s+strlen(s)));
        printf("\n");
    }
    return 0;
}
#include <cstdio>
#include <cstring>
#include <algorithm>
using std::sort;

char s[50], a[50];
int l;

void print_permutation(int cur)
{
    if (cur == l) {
        a[cur] = '\0';
        printf("%s\n", a);
        return;
    }
    else {
        for (int i = 0; i < l; i++)
            if (!i || s[i] != s[i-1]) {
                int c1 = 0, c2 = 0;
                for (int j = 0; j < cur; j++) if (s[i] == a[j]) c1++;
                for (int j = 0; j < l; j++) if (s[i] == s[j]) c2++;
                if (c1 < c2) {
                    a[cur] = s[i];
                    print_permutation(cur+1);
                }
            }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t--) {
        scanf("%s", s);
        l = strlen(s);
        sort(s, s+l);
        print_permutation(0);
        printf("\n");
    }
    return 0;
}

题目

Description

Generating permutation has always been an important problem in computer science. In this problem you will have to generate the permutation of a given string in ascending order. Remember that your
algorithm must be efficient.

Input

The first line of the input contains an integer n, which indicates how many strings to follow. The next n lines contain n strings. Strings will only contain alpha numerals and never contain any space. The maximum length of the string is 10.

Output

For each input string print all the permutations possible in ascending order. Not that the strings should be treated, as case sensitive strings and no permutation should be repeated. A blank line should follow each output set.

Sample Input

3
ab
abc
bca

Sample Output

ab
ba

abc
acb
bac
bca
cab
cba

abc
acb
bac
bca
cab    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值