Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 15 Jan, 2021

Easy

```
1. There might be duplicates present in the array.
2. The order of the permutations in the output does not matter.
3. Do not use any kind of in-built library functions to find the answer.
```

```
The first line contains the integer N, denoting the size of the array.
The second line contains N space-separated integers denoting the array elements.
```

```
The output contains K lines, where each line contains N space-separated integers denoting one of the unique permutations of the given array.
Output for each test case must be in a separate line.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
1 <= N <= 6
Time Limit: 1 sec
```

- Since we can not manually find the permutations, the best approach is to solve this problem by backtracking.
- So for solving the problem by backtracking, let us have a recursive function generatePerm() which will generate all the permutations of the array.
- Since we do not want to generate the same permutations again and again, we can use a map of vectors and int to check whether we have already generated a permutation or not. Let the map name be isGenerated.
- Let 'CURR' be the array which will store the current permutation that we are working with. If the size of current is ‘N’, that means we have successfully generated a permutation and we can print it.
- Let ‘i’ = 0 initially, which points to the current element of the array
- Now for all ‘j’ = ‘i’ to ‘N’ - 1, do the following:
- Push ‘ARR[i]’ into ‘CURR’.
- Swap(‘ARR[i]’ , ‘ARR[j]’) to generate new permutation.
- Call generatePerm() from ‘i’ + 1.
- Pop the last element from 'CURR'.

- After the end of this loop, we will have all the unique permutations of the array.

Similar problems

Prime Digit Sum

Hard

Posted: 17 Apr, 2022

Prime Digit Sum

Hard

Posted: 17 Apr, 2022

Mario And His Princess

Moderate

Posted: 12 May, 2022

Combination Sum III

Moderate

Posted: 25 May, 2022

Combination Sum III

Moderate

Posted: 25 May, 2022

Combination Sum III

Moderate

Posted: 25 May, 2022

Combination Sum III

Moderate

Posted: 25 May, 2022

Generate All Strings

Moderate

Posted: 9 Jul, 2022

Generate All Strings

Moderate

Posted: 9 Jul, 2022

8-Queen Problem

Easy

Posted: 19 Dec, 2022