算法 字符串的排列组合

package ACM;

import java.util.ArrayList;
import java.util.TreeSet;

public class Solution13 {

    public  ArrayList<String> Permu(String str){
        ArrayList<String> result = new ArrayList<String>();

        if (str==null || str.length()==0){
            return result;
        }

        char[] chars = str.toCharArray();
        TreeSet<String> temp = new TreeSet<>();
        Permu(chars,0,temp);
        result.addAll(temp);
        return result;
    }
    public void Permu(char[]chars, int begin, TreeSet<String> result){
        if(chars==null || chars.length==0|| begin<0 ||begin>chars.length-1){return;}

        if(begin==chars.length-1){
            result.add(String.valueOf(chars));
        }else {
            for(int i = begin; i<chars.length-1; i++){
                swap(chars,begin,i);
                Permu(chars,begin+1,result);
                swap(chars,begin,i);
            }
        }

    }
 public void swap(char[] x, int a, int b){
         char t = x[a];
         x[a]=x[b];
         x[b]=t;
 }

  public static  void main(String[] args){
     String s = "adsgf";
      Solution13 s1 = new Solution13();
      System.out.println(s1.Permu(s));
  }


}

  

posted @ 2018-04-14 10:57  toov5  阅读(145)  评论(0编辑  收藏  举报