public class Permutations {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> ans = permute(nums);
System.out.println(ans.toString());
}
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length == 0) {
return ans;
}
recurse(nums, ans, 0);
return ans;
}
private static void recurse(int[] nums, List<List<Integer>> ans, int depth) {
int len = nums.length;
if (depth == len - 1) {
List<Integer> solution = new ArrayList<>();
for (int n : nums) {
solution.add(n);
}
ans.add(solution);
return;
}
for (int j = depth; j < len; j++) {
swap(nums, depth, j);
recurse(nums, ans, depth + 1);
swap(nums, depth, j);
}
}
static void swap(int[] nums, int x, int y) {
int tmp = nums[x];
nums[x] = nums[y];
nums[y] = tmp;
}
}