zoukankan      html  css  js  c++  java
  • 剑指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();
        }
    
    }
    

       

  • 相关阅读:
    面向对象三大特征------多态
    接口的概念
    面向对象(抽象类)
    面向对象三大特征------继承
    面向对象三大特征------封装
    成员变量和局部变量的区别
    20180822 ajax post 方式请求
    20180815 权限
    20180815 视图
    20180814 夜晚小目标
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11965862.html
Copyright © 2011-2022 走看看