This is my first question on StackOverflow.
I need to find unique permutations of size n which will have unique elements. I have already written a logic for that (for now it is limited to size 3), but it is slow, as in the worst case, it gives n*n*n complexity. Also it won't work for size more than 3.
What should I do in order to reduce the complexity, and make it work for any size of permutation?
Example:
Input :
ABCD
Output :
A B C
A B D
A C D
B C D
(Adding the list to a set will improve the speed a little bit, but it won't affect the time complexity for a list with less number of duplicates).
Here's my code:
Set<String> permute(List<String> input, int limit) {
Set<String> one = new HashSet<>();
Set<String> two = new HashSet<>();
Set<String> three = new HashSet<>();
for (int i = 0; limit > 0 && i < input.size(); i++) {
one.add(input.get(i));
for (int j = i + 1; limit > 1 && j < input.size(); j++) {
String temp = input.get(i) + "-" + input.get(j);
two.add(temp);
for (int k = j + 1; limit > 2 && k < input.size(); k++) {
temp = input.get(i) + "-" + input.get(j) + "-" + input.get(k);
three.add(temp);
}
}
}
switch(limit) {
case 1:
return one;
case 2:
return two;
case 3:
return three;
default:
return new HashSet<>();
}
}
Thanks