输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。...

package myprac.LeetCode;

import java.util.ArrayList;
import java.util.List;

public class StringPermutation {
   /* public static ArrayList Permutation(String str) {
        ArrayList list = new ArrayList<>();
        if(str==null || str.length()==0){
            return list;
        }
        char[] chars = str.toCharArray();
        sort(list,0,chars);
        Collections.sort(list);
        return list;
    }
    private static void sort(ArrayList list, int i, char[] chars) {
        if(i==chars.length-1){//i=2执行
            list.add(new String(chars));
        }
        for(int index = i;i*/
   public static List> permute(String str) {
     
       List> list = new ArrayList<>();
       
       backtrack(list, new ArrayList(), str.toCharArray());
       return list;
   }

    private static void backtrack(List> list, List tempList, char[] chars){
       
        if(tempList.size() == chars.length){
            
            list.add(new ArrayList<>(tempList));
        } else{
            for(int i = 0; i < chars.length; i++){
                if(tempList.contains(chars[i])){
                    continue;
                }
                
                tempList.add(chars[i]);
               
                backtrack(list, tempList, chars);

                
                tempList.remove(tempList.size() - 1);
            }
        }
    }

    public static void main(String[] args){
       String string = "abc";
        System.out.println(permute(string));
    }
}

 

转载于:https://www.cnblogs.com/q-1993/p/10864393.html

你可能感兴趣的:(输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。...)