Permutations in Java: Explanation & Practice
Generate all permutations of an array
Problem summary
Given an array of distinct integers, return all possible permutations. A permutation is a rearrangement of all elements.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
// Backtracking: try each unused element at each position
// Use visited array or swap technique
// Print all permutations
}
}Expected output and test cases
- [1,2,3] → 6 permutations
[1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1]
- [0,1] → 2 permutations
[0,1] [1,0]
- [1] → just [1]
[1]
Hints
- For each position, try all unused elements
- Mark element as used, recurse, then unmark (backtrack)
- Base case: when current permutation has all elements
- Total permutations = n!
Related Data Structures & Algorithms exercises
- Practice Capacity To Ship Packages in Java
- Practice Subsets (Power Set) in Java
- Practice Combination Sum in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler