zoukankan      html  css  js  c++  java
  • 全排列问题

    全排列问题

    基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题
     
    给出一个字符串S(可能又重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",
    输出为:
     
    1123
    1132
    1213
    1231
    1312
    1321
    2113
    2131
    2311
    3112
    3121
    3211
    Input
    输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)
    Output
    输出S所包含的字符组成的所有排列
    Input示例
    1312
    Output示例
    1123
    1132
    1213
    1231
    1312
    1321
    2113
    2131
    2311
    3112
    3121
    3211

    ①用STL//教程在紫书187页
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    char QAQ[15];
    int n;
    
    int main()
    {
        scanf("%s",QAQ);
        n=strlen(QAQ);
        sort(QAQ,QAQ+n);
        do
        {
            puts(QAQ);
        }
        while (next_permutation(QAQ,QAQ+n));
        return 0;
    }
    View Code

    ②用递归代替重,递归里放一个循环

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <vector>
    #include <map>
    using namespace std;
    typedef string::const_iterator sit;
    bool vis[9];
    map<string,bool> m;
    void dfs(const string& s,sit pos,string& st) {
        if (st.size()==s.length()&&m.find(st)==m.end()) {
            m[st]=true;
            cout<<st<<endl;
            return;
        }
        for (sit i=s.begin(); i!=s.end(); ++i)
            if (vis[i-s.begin()]==false) {
                vis[i-s.begin()]=true;
                st.push_back(*i);
                dfs(s,i+1,st);
                st.erase(st.end()-1,st.end());
                vis[i-s.begin()]=false;
            }
    }
    
    int main() {
        string s;
        cin>>s;
        sort(s.begin(),s.end());
        string temp;
        dfs(s,s.begin(),temp);
        return 0;
    }
    View Code





  • 相关阅读:
    第三章 运算符与表达式
    python 第二章 对象与类型
    线段树区间染色+注意事项
    ACM-ICPC北京赛区2018重现赛 A题
    删除元组
    修改元组
    访问元组
    Python 元组
    Python List sort()方法
    hdu4501——小明系列故事——买年货(多维背包)
  • 原文地址:https://www.cnblogs.com/gc812/p/5916065.html
Copyright © 2011-2022 走看看