题解 | #字符串的排列#
字符串的排列
http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> ans;
if(str.length() == 0) return ans;
permutation(ans,str,0);
return ans;
}
void permutation(vector<string> &ans,string str,int index ){
if(index >= str.length()){
//找到了一个答案
//对于去除重复排列,还有一种非常简单的方案,就是再保存某一个排列时,直接判断该排列情况是否
//已经存在于答案集里,存在则不再插入。
ans.push_back(str);
return;
}
for(int i=index;i<str.length();i++){
int j = i-1;
int flag = 0;
while(j>=index){ //aa \ abb 这种情况需要添加这个while循环来去重
if(i!=j && str[i] == str[j]) //判断当前的字母与前面的字符是否重复,重复,则flag =1,for循环continue;
{flag = 1;break;}
j--;
}
if(flag) continue;
swap(str[i],str[index]); //交换
permutation(ans,str,index + 1);
swap(str[i],str[index]); //交换回来
}
}
};