46. Permutations
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
Example:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
nums
distinct?
nums
?
To generate all permutations of a list of distinct integers, we can use a backtracking approach. This approach involves constructing permutations in a depth-first manner.
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new ArrayList<>(), result);
return result;
}
private void backtrack(int[] nums, List<Integer> current, List<List<Integer>> result) {
// Base case: If the current list has the same size as nums, a permutation is complete
if (current.size() == nums.length) {
result.add(new ArrayList<>(current));
return;
}
// Recursive case: Try adding each number to the current list
for (int num : nums) {
if (!current.contains(num)) { // Ensure we don't add the same number
current.add(num);
backtrack(nums, current, result);
current.remove(current.size() - 1); // Backtrack to try the next possibility
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3};
List<List<Integer>> permutations = solution.permute(nums);
for (List<Integer> permutation : permutations) {
System.out.println(permutation);
}
}
}
The time and space complexity for generating permutations of a list of size n
are as follows:
O(n * n!)
n!
permutations, and each permutation takes O(n)
time to generate.O(n)
O(n)
. The total space for storing all permutations is also significant but usually considered secondary to the main algorithm’s complexity.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?