Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Example 1:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:
Input: nums = [0,1] Output: [[0,1],[1,0]]
Example 3:
Input: nums = [1] Output: [[1]]
Constraints:
1 <= nums.length <= 6-10 <= nums[i] <= 10- All the integers of
numsare unique.
Approach: Backtracking with Used Array
Algorithm
- Use a recursive backtracking function that builds a permutation one element at a time
- Track which elements have already been used with a
boolean[] usedarray - When the current permutation has the same length as
nums, add a copy to the result - Otherwise, iterate through every element, skip used ones, add it, recurse, then backtrack
Time & Space Complexity
- Time Complexity: O(n ยท n!) - there are n! permutations, each costing O(n) to build
- Space Complexity: O(n) - recursion depth plus the used array (excluding the output)
Java Implementation
import java.util.ArrayList;
import java.util.List;
public class Permutations {
/**
* Return all possible permutations of the array.
* @param nums Array of distinct integers
* @return List of all permutations
*/
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
backtrack(nums, new boolean[nums.length], new ArrayList<>(), result);
return result;
}
private static void backtrack(int[] nums, boolean[] used,
List<Integer> current, List<List<Integer>> result) {
if (current.size() == nums.length) {
result.add(new ArrayList<>(current));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
current.add(nums[i]);
backtrack(nums, used, current, result);
used[i] = false;
current.remove(current.size() - 1);
}
}
// Test method
public static void main(String[] args) {
int[] nums1 = {1, 2, 3};
System.out.println("Input: nums = [1,2,3]");
System.out.println("Output: " + permute(nums1));
// Expected: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
int[] nums2 = {0, 1};
System.out.println("Input: nums = [0,1]");
System.out.println("Output: " + permute(nums2));
// Expected: [[0,1],[1,0]]
int[] nums3 = {1};
System.out.println("Input: nums = [1]");
System.out.println("Output: " + permute(nums3));
// Expected: [[1]]
}
}
Key Points
- Distinct Elements: No duplicate handling is needed since all integers are unique
- Used Tracking: The
usedarray prevents reusing an element within one permutation - Copy on Complete: Add
new ArrayList<>(current)to avoid sharing mutable references - Backtracking Pattern: Mark used -> add -> recurse -> unmark -> remove
- Small Constraint:
nums.length <= 6, so at most 720 permutations