题解 | 回溯是解决全排列问题的标准办法

全排列

https://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1

#include <iostream>
#include <string>
#include <map>
using namespace std;

void backtracking(int level,string s);
void mswap(char &a,char &b);
map<string,bool> m;
int main() 
{
    string s;
    while(cin>>s)
    {
        m.clear();
        backtracking(0,s);
        for(auto x:m)
        {
            cout<<x.first<<endl;
        }
    }
}
// 64 位输出请用 printf("%lld")

void backtracking(int level,string s)
{
    if(level==s.size())
    {
        m[s]=true;
    }
    for(int i=level;i<s.size();++i)
    {
        mswap(s[i],s[level]);
        backtracking(level+1,s);
        mswap(s[i],s[level]);
    }
}

void mswap(char &a,char &b)
{
    char temp=a;
    a=b;
    b=temp;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务