225k views
1 vote
Write a recursive method that displays all permutations of a given array of integers.

Here is a sample run of the program:
Enter the array size: 3
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

User QiGuar
by
7.9k points

1 Answer

3 votes

Final answer:

To write a recursive method that displays all permutations of a given array of integers, follow these steps: create a recursive method, handle base case, iterate through array elements, and return the list of permutations. Learn how to implement this in Java.

Step-by-step explanation:

In order to write a recursive method that displays all permutations of a given array of integers, you can follow the following steps:

  1. Create a recursive method that takes the array as a parameter.
  2. If the length of the array is 1, return an array with the single element.
  3. Otherwise, for each element in the array, do the following:
  • Create a copy of the array without the current element.
  • Call the recursive method with the new array.
  • For each permutation returned by the recursive call, add the current element at the beginning and add the permutation to a list of permutations.
Return the list of permutations.

Here is an example implementation in Java:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Permutation {
public static List<int[]> permute(int[] nums) {
List<int[]> result = new ArrayList<>();
if (nums.length == 1) {
result.add(nums);
} else {
for (int i = 0; i < nums.length; i++) {
int[] copy = Arrays.copyOf(nums, nums.length - 1);
int[] prefix = new int[] { nums[i] };
for (int[] permutation : permute(copy)) {
int[] arr = new int[nums.length];
System.arraycopy(prefix, 0, arr, 0, 1);
System.arraycopy(permutation, 0, arr, 1, permutation.length);
result.add(arr);
}
}
}
return result;
}

public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
List<int[]> permutations = permute(nums);
for (int[] permutation : permutations) {
System.out.println(Arrays.toString(permutation));
}
}
}

When you run the program, it will output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
User Yuri Shkuro
by
8.2k points