剑指Offer第十八题:字符串的排列
题目描述
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
题目分析
将所有的字符排列出来打印,而且排列的类型会有多个,还会随着个数的增加而增加。该题应该使用回溯法,我也对回溯法理解的模模糊糊的,上学期老师的课没有认真听,前几天的阿里和腾讯的笔试都有回溯法的编程题,当时没有做出来,一脸懵逼,今天刷到这道题,才发现....不好好听课的代价。
回溯法,我们得先找到回溯的那个点。这道题的原理就是,一个一个的替换,替换到最后一个时,那么就是个完整的排列了。所有我们只需要i==str.lenth的情况。
源代码
1 public class Solution { 2 public ArrayList<String> Permutation(String str) { 3 ArrayList<String> std=new ArrayList<>(); 4 if(str==null||str.length()==0) 5 return std; 6 per(std, str.toCharArray(), 0); 7 Collections.sort(std); 8 return (ArrayList)std; 9 } 10 public void per(ArrayList<String> list,char[] str,int j) { 11 if(j==str.length) { 12 if(!list.contains(String.valueOf(str))) { 13 list.add(new String(str)); 14 } 15 return; 16 } 17 for(int i=j;i<str.length;i++) { 18 swap(str, i, j); 19 per(list, str, j+1); 20 swap(str, i, j); 21 } 22 23 } 24 25 public void swap(char[] str,int i,int j) { 26 if(i!=j) { 27 char temp=str[i]; 28 str[i]=str[j]; 29 str[j]=temp; 30 } 31 } 32 }