首页 > 解决方案 > C ++,如果某些条目重复,则输出所有可能的排列(递归算法)

问题描述

问题

时间限制:1.00 秒内存限制:512 MB

给定一个字符串,您的任务是生成可以使用其字符创建的所有不同字符串。

输入

唯一的输入行有一个长度为 n 的字符串。每个字符都在 a-z 之间。

输出

然后打印 k 行:按字母顺序排列的字符串。整数 k:字符串的数量。

约束 1≤n≤8

代码

#include<bits/stdc++.h>
using namespace std;


void fun(int c[],int &x, string s,int l,int n)
{
    //To use a Recursive Algorithms to find all the n! ways
    if(l==n)
    {
        // in all the n! ways this below loop is to impose the 
        // order in the terms which were same but considered different 
        // in aaabc all the 3 a's are in the positions 0 , 1 , 2 so
        // but the below  Recursive Algorithms considers it to be 
        // a1a2a3 so this below loops is to place an order in them 
        int t=0;
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(s[c[i]]==s[c[j]]) {if(c[i]>c[j]){t++; break;} }
                if(t>0) break;
            }
            if(t>0) break;
        }

        // c[n] array is going to take the position of the characters
        // in the elements in s  
        // if not assigned the value would be 10
        if(t==0) { x++;
        for(int i=0;i<n;i++) { cout<<s[c[i]];}
        cout<<endl;}
    }

    else
    {
        for(int i=0;i<n;i++)
        {
            if(c[i]<10)continue;
            c[i]=l;
            fun(c,x,s,l+1,n);
            c[i]=10;
        }
    }
}



int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    string s; cin>>s;
    int n = s.length();

// 10 is not going to disturb any of the positioning because 
// maximum value of the is 8 
    int c[n]={10};
    int x=0;

    fun(c,x,s,0,n);
    cout<<x;
}

问题

对于任何输入,输出为 0,对于所有类型的输入,该函数仅输入两次。

标签: c++arraysalgorithmsortingrecursion

解决方案


推荐阅读