递归和动态规划——**字符串的全排列

打印一个字符串的全部排列

 

 

public class CC_Print_All_Permutation {
    public static void printAllPermutation(String str){
        if(str == null || str.length() == 0) return;
        char[] chars = str.toCharArray();
        permutation(chars, 0);
    }

    public static void permutation(char[] chars, int index){
        if(index == chars.length){
            System.out.println(String.valueOf(chars));
            return;
        }
        HashSet<Character> hashSet = new HashSet<>();
        for(int i = index; i < chars.length; i++){
            if(!hashSet.contains( chars[i])){
                hashSet.add(chars[i]);
                swap(chars, index, i);
                permutation( chars, index + 1 );
                swap(chars, index, i);
            }
        }
    }

    public static void swap(char[] chars, int i, int j){
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }

    public static void main(String[] args){
        printAllPermutation( "abc" );
    }
}

  

 

posted @ 2018-04-28 08:55  SkyeAngel  阅读(517)  评论(0编辑  收藏  举报