剑指offer-面试题38-字符串的排列-全排列

/*
题目:
	输入字符串,打印字符串的所有排列。
	输入acc,输出[acc, cac, cca]。
*/
/*
思路:
	将字符串看作两部分,第一个字符串和后面的部分。
	将第一个字符串与后面字符串依次交换。求后面部分的全排列。
	进入递归,将第二个字符串与后面的字符串依次交换,求后面部分的全排列。
	...
	使用set去重。
*/
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<set>

using namespace std;

set<string> all;

void getAll(string str,int beginIndex){
    if(str.size() == beginIndex){
        //cout<<str<<",";
        all.insert(str);
    }else{
        for(int i = beginIndex; i < str.size(); i++){
			//将第一个字符串与后面字符串依次交换
            char temp = str[i];
            str[i] = str[beginIndex];
            str[beginIndex] = temp;
			//求后面部分的全排列
            getAll(str,beginIndex+1);
			//将第一个字符串与后面字符交换回来
            str[beginIndex] = str[i];
            str[i] = temp;
        }
    }
}

int main(){
    string str;
    while(getline(cin,str)){
        if(str == "")
            cout<<"[]"<<endl;
        else{
            cout<<"[";
            getAll(str,0);
            set<string>::iterator it = all.begin();
            while(it != all.end()){
                cout<<(*it);
                if((++it) != all.end())
                    cout<<", ";
            }
            //cout<<(*it);
            cout<<"]";
        }
        all.clear();
    }

}

   

猜你喜欢

转载自www.cnblogs.com/buaaZhhx/p/11965862.html