Skip to content

Instantly share code, notes, and snippets.

@alibitek
Created September 14, 2015 06:15
Show Gist options
  • Select an option

  • Save alibitek/08e159b10ebab6d8725b to your computer and use it in GitHub Desktop.

Select an option

Save alibitek/08e159b10ebab6d8725b to your computer and use it in GitHub Desktop.
Permutations
import java.util.HashSet;
public class Permutations {
public static HashSet<String> permutations(String str) {
return permutations("", str);
}
private static HashSet<String> permutations(String prefix, String str) {
HashSet<String> result = new HashSet<>();
int n = str.length();
if (n == 1) result.add(prefix + str);
else {
for (int i = 0; i < n; i++)
result.addAll(permutations(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1)));
}
return result;
}
public static void main(String[] args) {
permutations("abba").forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment