LeetCode 46: Permutations
Problem Description
Explanation:
To generate all possible permutations of an array of distinct integers, we can use backtracking. The idea is to swap elements in the array to create different permutations. We start with the original array and recursively swap elements to generate all possible permutations. We keep track of the current index and swap elements accordingly.
- Start with an empty result list to store all permutations.
- Create a helper function that takes the current index, the array of integers, and the result list as parameters.
- If the current index is equal to the length of the array, add a copy of the array to the result list (a permutation).
- Iterate over the array starting from the current index.
- Swap the current element with the element at the current index.
- Recursively call the helper function with the incremented index.
- Swap back the elements to maintain the original array.
- After the recursion, the result list will contain all permutations.
Time complexity: O(N * N!) - where N is the number of elements in the input array. Space complexity: O(N) - additional space is used for recursion stack and result list.
Solutions
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
permuteHelper(nums, 0, result);
return result;
}
private void permuteHelper(int[] nums, int index, List<List<Integer>> result) {
if (index == nums.length) {
List<Integer> permutation = new ArrayList<>();
for (int num : nums) {
permutation.add(num);
}
result.add(permutation);
} else {
for (int i = index; i < nums.length; i++) {
swap(nums, index, i);
permuteHelper(nums, index + 1, result);
swap(nums, index, i);
}
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
Related LeetCode Problems
Loading editor...