Created
September 14, 2015 06:15
-
-
Save alibitek/08e159b10ebab6d8725b to your computer and use it in GitHub Desktop.
Permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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