2017-09-17 2 views
2

Javaで再帰を使用して、指定された文字列のすべての可能な順列を計算しようとしています。しかし、自分のコードに何が問題なのか分かりません。文字列のすべての可能な順列を再帰的に計算するJava

public static ArrayList<String> computeAllPossiblePermutations(String str) 
{ 
    ArrayList<String> perms = new ArrayList<>(); 

    //base case 
    if (str.length() == 1) 
     perms.add(str); 

    else 
    { 
     //loop over the string 
     for (int i = 0; i < str.length() - 1; i++) 
     { 
      //make a subset of the string excluding the first char 
      String sub = str.substring(i+1, str.length()); 
      //compute permutations of the subset 
      ArrayList<String> subPerms = computeAllPossiblePermutations(sub); 
      //add the first char that we excluded at the start of each permutations 
      for (String s : subPerms) 
      { 
       s = str.charAt(i) + s; 
       perms.add(s); 
      } 
     } 

    } 

    return perms; 
} 

は、任意のヘルプをお願い申し上げ:

は、ここに私のアルゴリズムです。ありがとう!

+1

。あなたが悪い結果を得ているなら、あなたが実際に得ているものと何が得られるかを示すべきです。 – Carcigenicate

答えて

0

いくつかの問題があります。

  1. は、次の行:String sub = str.substring(i+1, str.length());はしばらく、同じラインもそのまま残っている部分文字列の「ブロック」としてインデックスi後に何を扱う最初の文字
  2. を無視順列を生成するために、現在の(最初の)文字を文字列の残りの2文字の間に挿入する必要があります。各置換のためにそれを行います。
  3. s = str.charAt(i) + s;は#2で同じ誤りを繰り返す

は、ここで修正案です:私たちはどちらか間違っているのか分からない


public static ArrayList<String> computeAllPossiblePermutations(String str) { 
    ArrayList<String> perms = new ArrayList<>(); 
    if (str.length() == 1) { 
     perms.add(str); 
    } else { 
     String chr = str.substring(0,1); 
     String rest = str.substring(1); 
     ArrayList<String> subPerms = computeAllPossiblePermutations(rest); 
     for (String s : subPerms) { 
      for (int j = 0; j <= s.length(); j++) { 
       String newPerm = s.substring(0,j) + chr + s.substring(j); 
       perms.add(newPerm); 
      } 
     } 
    } 
    return perms; 
} 
+1

重複順列を避けるために 'Set perms = new HashSet <>();'を使うことをお勧めします。 'ArrayList'を使うと、' aaa'のような入力に対して同じ順列を6回得ることができます。 – c0der

+1

入力に同じ文字が複数回含まれる場合は、* Set *を実際に使用する必要があります。 – alfasin

関連する問題