题解 | 全排列(层序遍历)

全排列

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

比递归直接构造要慢,不过思路和代码简单粗暴;

a的2个位置分别插入b

abba的3个位置分别插入c;

...最后排个序;

#include <iostream>
#include <string>
#include <list>
using namespace std;
int main() {
    char c; cin>>c;
    list<string> que={string()+c};
    while(cin>>c && c!='\n'){
        int sq=que.size();
        for(int j=0; j<sq; ++j, que.pop_front()){
            for(int i=0; i<=que.front().size(); ++i){
                string tmp=que.front();
                tmp.insert(tmp.begin()+i, c);
                que.push_back(tmp);
            }; 
        }
    }
    que.sort();
    for(auto & i : que) cout<<i<<endl;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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