Question:
How to find all the possible unique permutations of the array using Java

Summary

Consider the following aspect:

Assume that sequence A is greater than sequence B in case there is an index i for which the function Aj=Bj for all j<i and Ai>Bi. 


Let’s assume:

Using two function- findPerms and uniquePerms


Solution


//User function Template for Java


class Solution {

    ArrayList<ArrayList<Integer>> findPerms(ArrayList<Integer> arr, int n) {

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

        if (n == 1) {

            ArrayList<Integer> temp = new ArrayList<>();

            temp.add(arr.get(0));

            ans.add(temp);

            return ans;

        }


        for (int i = 0; i < n; i++) {

            if (i > 0 && arr.get(i - 1) == arr.get(i))

                continue;


            int removedElement = arr.remove(i);

            ArrayList<ArrayList<Integer>> permsNext = findPerms(arr, n - 1);

            for (int j = 0; j < permsNext.size(); j++) {

                permsNext.get(j).add(0, removedElement);

                ans.add(permsNext.get(j));

            }

            arr.add(i, removedElement);

        }


        return ans;

    }

    ArrayList<ArrayList<Integer>> uniquePerms(ArrayList<Integer> arr , int n) {

        Collections.sort(arr); //sort the arraylist

        return findPerms(arr, n);

    }

};


Suggested blogs:

>How to make count consistent across numbers?


>How to return the subarray indexes from left to right using Java

>How to return the sum of subarray with maximum sum

>How to print all the paths from the root with a specified sum using Java

>Building Web API using ASP.NET (C#)

>Built Web API using ASP.NET (C#)


Nisha Patel

Nisha Patel

Submit
0 Answers