Question:
Given a string S of length N.
Print all permutations of the string in separate lines.
Input Size: 1 <= N <= 100000
Sample Testcases :
INPUT:
123
OUTPUT:
123
231
321
213
312
132
Answer:
Steps to find all permutations of any number:
- We are going to use Recursion for calculating the permutations. Create a method called "getPermutations", and create a Permutations array inside the method that will hold all the permutations. Let's start with the base condition (Where the recursion stops).
- The base condition will be when the number has only one digit simply add it to the permutations array and return the array.
- If the number has more digits, then iterate through all the digits.
- On each iteration, find the current digit (store it in one variable) and find all other digits (store it in another variable).
- Call the recursive function "getPermutations" and pass the other digits variable created in the above step. We will expect this to return an array of all permutations of the other digits variable.
- For each permutation received, append to the current digit and add it to the Permutations array.
- Since we are iterating the actual number, this will be done for all digits.
- Outside the for loop simply return the Permutations array.
Comments
Post a Comment