Skip to content
This repository has been archived by the owner on Nov 11, 2021. It is now read-only.

PermutationDemo generates duplicate #8

Open
skills-up opened this issue Nov 21, 2019 · 1 comment
Open

PermutationDemo generates duplicate #8

skills-up opened this issue Nov 21, 2019 · 1 comment

Comments

@skills-up
Copy link

skills-up commented Nov 21, 2019

The PermutationDemo.java program will lead to duplicates. A quick fix is to do the inner loop on the clone of the array.

    public static void printPermutn(int[] arr, int index) {
        int len = arr.length;

        if (index == (len-1)) {
            for(int i=0; i<len; i++) System.out.print(arr[i]);
            System.out.println();
        } else {
            int[] a = arr.clone();
            for(int i=index; i<len; i++) {
                int t = a[i];
                a[i] = a[index];
                a[index] = t;
                printPermutn(a, index+1);
            }
        }
    }
@anupamhaldkar
Copy link

You can just add swapping one more time after recursive condition so that array becomes original. ⛳

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants