2014-12-03 35 views
0

所以我採用了經典的算法排列是如何將一個字符串的所有可能的排列組合到一個數組中?

private static void permutation(String prefix, String str) { 
    int n = str.length(); 
    if (n == 0) System.out.println(prefix); 
    else { 
     for (int i = 0; i < n; i++) 
      permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); 
    } 
} 

我無法弄清楚如何做的唯一的事情就是如何將排列存儲到一個數組,而不是隻打印出來。任何幫助表示讚賞。

回答

1

試試這種方法。這將返回排列列表

private static List<String> permutation(String prefix, String str) { 
    List<String> permutations = new ArrayList<>(); 
    int n = str.length(); 
    if (n == 0) { 
     permutations.add(prefix); 
    } 
    else { 
     for (int i = 0; i < n; i++) 
      permutations.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n))); 
    } 
    return permutations; 
} 

使用數組。需要JAVA 8

private static String[] permutation(String prefix, String str) { 
    String[] permutation = new String[]{}; 
    int n = str.length(); 
    if (n == 0) { 
     permutation = new String[]{prefix}; 
    } 
    else { 
     for (int i = 0; i < n; i++) 
      permutation = Stream.concat(Arrays.stream(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n))), 
        Arrays.stream(permutation)).toArray(String[]::new); 

    } 
    return permutation; 
} 
0

您也可以將排列列表的引用傳遞給排列方法本身。這具有僅創建一個列表的優點。

private static List<String> permutation(String str) { 
    List<String> perms = new ArrayList<>(); 
    permutation("", str, perms); 

    return perms; 
} 

private static void permutation(String prefix, String str, List<String> perms) { 
    int n = str.length(); 
    if (n == 0) { 
    perms.add(prefix); 
    } else { 
    for (int i = 0; i < n; i++) 
     permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1,n), perms); 
    } 
} 

List<String> perms = permutation("abcd"); 
相關問題