Question:
Finding all possible permutations of a given string using Java

Summary:

Suppose we are given a string S with N number of elements in it. The task is to find all the possible permutations of a given string using Java code.


Solution:

//User function Template for Java


class Solution

{

    public void permute(ArrayList<String>ans,String s,String temp,int index,boolean vis[])

    {

        if(temp.length()==s.length())

        {

            ans.add(temp);

            return;

        }

        if(index==s.length())

        {

          

            return;

        }

        

        //take

        if(!vis[index])

        {

             vis[index]=true;

             permute(ans,s,temp+s.charAt(index),0,vis);

              vis[index]=false;

        }

       

        //not take

        permute(ans,s,temp,index+1,vis);

    }

    public ArrayList<String> permutation(String S)

    {

        //Your code here

        ArrayList<String>ans=new ArrayList<>();

        permute(ans,S,"",0,new boolean[S.length()]);

        Collections.sort(ans);

        return ans;

    }

   


Explanation:

Recursive Permutation Function:

The permute method recursively generates permutations of the input string s, appending each permutation to the result list ans.


Base Cases:

  • When the length of the current permutation matches the length of the input string, it's added to the result list.

  • When the index reaches the length of the input string, the method returns without further processing.


Permutation Generation:

For each character in the input string, it explores two possibilities: including it in the current permutation or excluding it.


Recursion and Backtracking:

  • After including a character in the permutation, it calls itself recursively with the updated parameters.

  • Backtracking is employed by marking characters as visited (vis) and unvisited after each recursive call.


Generating Permutations:

The permutation method initializes an empty list and calls permute to generate permutations.

It sorts the list of permutations in lexicographically sorted order before returning it.


Answered by: >user_5sdh3t87opj

Credit:> >Geeksforgeeks


Suggested blogs:

>How to Upload files and JSON data in the same request with Angular?

>How to make a single result from a database using MySQL?

>How to Make New Model/Controller/Migration in Laravel?

>How to make non-programmers to run a Python program?

>How to Use RTK Queries in a React App?

>How you can create array with associative array in other array php?

>Integrate SASS into the build and consume a UI toolkit

>Invoking Python script from scons and pass ARGLIST

>Migrate From Haruko To AWS App: 5 Simple Steps

>PHP cURL to upload video to azure blob storage

>PHP Error Solved: htaccess problem with an empty string in URL

>How you can send email from a shared inbox in Python


Submit
0 Answers