...

/

Permutations (medium)

Permutations (medium)

Problem Statement

Given a set of distinct numbers, find all of its permutations.

Permutation is defined as the re-arranging of the elements of the set. For example, {1, 2, 3} has the following six permutations:

  1. {1, 2, 3}
  2. {1, 3, 2}
  3. {2, 1, 3}
  4. {2, 3, 1}
  5. {3, 1, 2}
  6. {3, 2, 1}

If a set has ‘n’ distinct elements it will have n!n! permutations.

Example 1:

Input: [1,3,5]
Output: [1,3,5], [1,5,3], [3,1,5], [3,5,1], [5,1,3], [5,3,1]

Try it yourself

Try solving this question here:

import java.util.*;
class Permutations {
public static List<List<Integer>> findPermutations(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// TODO: Write your code here
return result;
}
public static void main(String[] args) {
List<List<Integer>> result = Permutations.findPermutations(new int[] { 1, 3, 5 });
System.out.print("Here are all the permutations: " + result);
}
}

Solution

This problem follows the Subsets pattern and we can follow a similar Breadth First Search (BFS) approach. However, unlike Subsets, every permutation must contain all the numbers.

Let’s take the example-1 mentioned above to generate all the permutations. Following a BFS approach, we ...