剑指OFFER之字符串的排列

题目描述: 

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。  

输入:

每个测试案例包括1行。

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

输出:

对应每组数据,按字典序输出所有排列。 

样例输入:
abc
BCA
样例输出:
abc
acb
bac
bca
cab
cba
ABC
ACB
BAC
BCA
CAB
CBA


Code:
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <string>
 
using namespace std;
 
const int arrSize=100;
bool mark[arrSize];
string str;
vector<char> answer;
 
void initMark(){
    int len=str.size();
    for(int i=0;i<len;++i)
        mark[i]=true;
}
 
void DFS(vector<char> &answer){
    if(answer.size()==str.size()){
        vector<char>::iterator iter;
        for(iter=answer.begin();iter!=answer.end();++iter)
            printf("%c",*iter);
        printf("
");
        return;
    }
    for(vector<char>::size_type cnt=0;cnt<str.size();++cnt){
        if(mark[cnt]==true){
            if(cnt>0&&str[cnt]==str[cnt-1]&&mark[cnt-1]==false)
                continue;
            mark[cnt]=false;
            answer.push_back(str[cnt]);
            DFS(answer);
            mark[cnt]=true;
            answer.pop_back();
        }
    }
}
 
int main(){
    while(cin>>str){
        sort(str.begin(),str.end());
        initMark();
        DFS(answer);
    }
    return 0;
}
 
/**************************************************************
    Problem: 1369
    User: lcyvino
    Language: C++
    Result: Accepted
    Time:570 ms
    Memory:1520 kb
****************************************************************/
原文地址:https://www.cnblogs.com/Murcielago/p/4169891.html