题目:输出一个字符串的全排列,且重复的排列不重复输出。
注:经典回溯法题目,八皇后问题,正方体的八个顶点,电话号码对应英文单词等都是一种算法;
代码如下:
public class TraceBack {
public static void main(String []argc)
{
String str="abbc";
char[] ch=str.toCharArray();
TraceBack test=new TraceBack();
test.permutation(ch, 0);
}
public void permutation(char[] ch,int index)
{
if(index==ch.length-1)
{
System.out.println(new String(ch));
}
for(int i=index;i<ch.length;i++)
{
if(is_swap(ch,index,i)==true)
{
swap(ch,index,i);
permutation(ch,index+1);
swap(ch,index,i);
}
}
}
public void swap(char[]ch,int index,int i)
{
char temp=ch[index];
ch[index]=ch[i];
ch[i]=temp;
}
//当该字符在以前没有出现过,则交换;
public boolean is_swap(char[] ch,int index,int i)
{
for(int k=index;k<i;k++)
{
if(ch[k]==ch[i])
{
return false;
}
}
return true;
}
}
public class Solution {
public ArrayList<String> Permutation(String str) {
if(str == null || str.trim().length() == 0){
return new ArrayList();
}
ArrayList<String> array = new ArrayList();
char[] chars = str.toCharArray();
perm(chars,0,array);
Collections.sort(array);
return array;
}
private void perm(char[] chars,int index, ArrayList<String> array) {
if(index == chars.length-1) {
array.add(new String(chars));
return;
}
for (int i=index;i<chars.length;i++){
if(is_swap(chars,index,i)==true){
swap(chars,i,index);
perm(chars,index+1,array);
swap(chars,i,index);
}
}
}
public boolean is_swap(char[] ch,int index,int i)
{
for(int k=index;k<i;k++)
{
if(ch[k]==ch[i])
{
return false;
}
}
return true;
}
private void swap(char[] chars,int i, int index){
char temp = chars[i];
chars[i] = chars[index];
chars[index] = temp;
}
}