剑指offer-面试题38-字符串的排列-全排列
2024-09-03 12:32:44
/*
题目:
输入字符串,打印字符串的所有排列。
输入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();
} }
最新文章
- flex中image控件source属性改变的例子
- Atitti css transition Animation differ区别
- Vysor:在电脑里控制你的安卓手机
- A configuration with this name already exists
- [转]Material Design Library 23.1.0的新变化与代码实战
- CentOS 安装 Sun JDK
- SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-003-@Conditional根据条件生成bean及处理profile
- iOS 开发工具
- java中实现查看今天是星期几的代码实现
- cdoj 1134 男神的约会 状压dp
- [转]java static final 初始化
- Mysql中让两个字段不同时相同的方法
- nested exception is java.lang.IllegalArgumentException: Pointcut is not well-formed
- Android反编译(未混淆的apk)
- 微服务化的大坑之一:当dubbo神器碰上共用注册中心和错误的暴露接口
- Perl中的hash类型
- Spring Cloud Stream如何消费自己生产的消息?
- git详细介绍
- 浅从System.Web.Http.Owin的HttpMessageHandlerAdapter看适配器模式
- Spring AOP 理论