weinan030416

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

递归求字符全排列

复制代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

const int N=10;
char n[N];
char path[N];
bool used[N];

void dfs(int u)
{
    if(u==strlen(n))
    {
        for(int i=0;i<strlen(n);i++)    cout<<path[i];
        cout<<endl;
        return;
    }
    for(int i=0;i<strlen(n);i++)
    {
        if(!used[i])
        {
            path[u]=n[i];
            cout<<"path["<<u<<"]"<<"=n["<<i<<"]"<<endl;
            used[i]=true;
            cout<<"used["<<i<<"]=true"<<endl;
            dfs(u+1);
            used[i]=false;
            cout<<"used["<<i<<"]=false"<<endl;
        }
        else
        {
            cout<<n[i]<<"已经使用了"<<endl;
        }
    }
}

int main()
{
    cin>>n;
    sort(n,n+strlen(n));
    dfs(0);
    return 0;
}
复制代码

输入abc

输出结果

path[0]=n[0]
used[0]=true
a已经使用了
path[1]=n[1]
used[1]=true
a已经使用了
b已经使用了
path[2]=n[2]
used[2]=true
abc
used[2]=false
used[1]=false
path[1]=n[2]
used[2]=true
a已经使用了
path[2]=n[1]
used[1]=true
acb
used[1]=false
c已经使用了
used[2]=false
used[0]=false
path[0]=n[1]
used[1]=true
path[1]=n[0]
used[0]=true
a已经使用了
b已经使用了
path[2]=n[2]
used[2]=true
bac
used[2]=false
used[0]=false
b已经使用了
path[1]=n[2]
used[2]=true
path[2]=n[0]
used[0]=true
bca
used[0]=false
b已经使用了
c已经使用了
used[2]=false
used[1]=false
path[0]=n[2]
used[2]=true
path[1]=n[0]
used[0]=true
a已经使用了
path[2]=n[1]
used[1]=true
cab
used[1]=false
c已经使用了
used[0]=false
path[1]=n[1]
used[1]=true
path[2]=n[0]
used[0]=true
cba
used[0]=false
b已经使用了
c已经使用了
used[1]=false
c已经使用了
used[2]=false

 

 

如果每个字母可以重复使用

 

复制代码
#include<iostream>
#include<cstring>
using namespace std;

char path[10];
char t[10];

void dfs(int n,int l)
{
    if(n==l)
    {
        n=0;
        cout<<path<<endl;
        return;
    }
    
    for(int i=0;i<l;i++)
    {
        path[n]=t[i];
        dfs(n+1,l);
    }
}

int main()
{

    cin>>t;
    dfs(0,strlen(t));
}
复制代码

 

posted on   楠030416  阅读(19)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示