您的位置:首页 > 其它

字符的全排列

2016-05-06 13:51 288 查看
输入一个字符串,打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

第一种情况:不存在重复的字符串

class Solution {
public:
vector<string> result;
vector<string> Permutation(string str) {
result.clear();
if(str.length()==0)
return result;

permute(str,0);
return result;
}
void permute(string str,int index)
{
if(str.length()-1==index)
{
result.push_back(str);
return ;
}
for(int i=index;i<str.length();++i)
{
char tt=str[i];
str[i]=str[index];
str[index]=tt;
permute(str,index+1);
tt=str[i];
str[i]=str[index];
str[index]=tt;
}
}
};


第二种情况,存在重复字符

class Solution {
public:
vector<string> result;
vector<string> Permutation(string str) {
result.clear();
if(str.length()==0)
return result;
permute(str,0);
return result;
}
void permute(string str,int index)
{
if(str.length()-1==index)
{
result.push_back(str);
return ;
}

for(int i=index;i<str.length();++i)
{

bool flag=true;
for (int j=index;j<i;++j)
{
if (str[j]==str[i])
{
flag=false;
break;
}
}
if(!flag)
continue;
char tt=str[i];
str[i]=str[index];
str[index]=tt;

permute(str,index+1);

tt=str[i];
str[i]=str[index];
str[index]=tt;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串全排列