707348. All Unique Permutations of an array
Here is the detailed Markdown blog post for the GeeksforGeeks problem "All Unique Permutations of an array":
All Unique Permutations of an array
Summary
Given a given array, generate all unique permutations of the array. This problem involves using recursion and backtracking to achieve the desired output.
Detailed Explanation
To solve this problem, we will use a recursive approach with backtracking. The basic idea is to fix one element at a time in the array, permute the remaining elements, and add the fixed element to each permutation.
Here's a step-by-step breakdown of the solution:
- Start by initializing an empty result set.
- Fix the first element of the array as the current element.
- Recursively generate all permutations of the remaining array (excluding the current element).
- For each permutation generated in step 3, add the current element to the beginning of the permutation and add it to the result set.
- Backtrack by restoring the original array and moving on to the next element.
- Repeat steps 2-5 until all elements have been processed.
Here's an example illustration:
Input: [1, 2, 3]
Fixed: 1
Permutations of remaining array: [[2, 3], [3, 2]]
Add 1 to each permutation: [[1, 2, 3], [1, 3, 2]]
Next element: 2
Fixed: 1
Permutations of remaining array: [[3]]
Add 1 and 2 to each permutation: [[1, 2, 3], [1, 3, 2], [2, 1, 3]]
Next element: 3
Fixed: 1
Permutations of remaining array: []
Add 1, 2, and 3 to each permutation: [[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2]]
Time complexity: O(n!), where n is the length of the input array. This is because there are n! permutations in total. Space complexity: O(n), as we need to store the result set and recursive function call stack.
Optimized Solutions
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<String> allPermutations(String[] arr) {
List<String> result = new ArrayList<>();
permute(arr, 0, "", result);
return result;
}
private static void permute(String[] arr, int start, String current, List<String> result) {
if (start == arr.length) {
result.add(current);
} else {
for (int i = start; i < arr.length; i++) {
String temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
permute(arr, start + 1, current + arr[start], result);
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
}
}
}
public static void main(String[] args) {
String[] arr = {"1", "2", "3"};
List<String> result = allPermutations(arr);
for (String s : result) {
System.out.println(s);
}
}
}