简体   繁体   中英

Perumations of size N java Array

In c++ permutations of an array can be generated using the function next_permutation . Is there a java equivalent of such a function to generate permutations of a size N array?

I am trying to come up with an equivalent recursive implementation but am struggling to solidify my logic.

There isn't a built-in function like this in java. You'll have to create your own, which is not that complicated. I'll provide an edit to this answer momentarily with a solution (not necessarily the best solution)

public static void printperms(int[] perm, boolean[] used, int k)
{
    if (k == perm.length) print(perm);
    for (int i=0; i<perm.length; i++) {
        if (!used[i]) {
           used[i] = true;
           perm[k] = i;
           printperms(perm, used, k+1);
           used[i] = false;
        }
    }
}

you can then create a new method, like so, to call it:

public void perms(int n){
    printperms(new int[n], new boolean[n], 0);
}

Lastly, where I have the print method, you can have the Array added to a list instead so that you can collect them all in a list, or you can just print it out. Your choice. Do with it as you please.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM