How would you calculate all possible permutations of 0 through N iteratively?

后端 未结 10 2614
一向
一向 2020-12-04 15:47

I need to calculate permutations iteratively. The method signature looks like:

int[][] permute(int n)

For n = 3 for example, the r

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 16:30

    How about a recursive algorithm you can call iteratively? If you'd actually need that stuff as a list like that (you should clearly inline that rather than allocate a bunch of pointless memory). You could simply calculate the permutation on the fly, by its index.

    Much like the permutation is carry-the-one addition re-reversing the tail (rather than reverting to 0), indexing the specific permutation value is finding the digits of a number in base n then n-1 then n-2... through each iteration.

    public static  boolean permutation(List values, int index) {
        return permutation(values, values.size() - 1, index);
    }
    private static  boolean permutation(List values, int n, int index) {
        if ((index == 0) || (n == 0))  return (index == 0);
        Collections.swap(values, n, n-(index % n));
        return permutation(values,n-1,index/n);
    }
    

    The boolean returns whether your index value was out of bounds. Namely that it ran out of n values but still had remaining index left over.

    And it can't get all the permutations for more than 12 objects. 12! < Integer.MAX_VALUE < 13!

    -- But, it's so very very pretty. And if you do a lot of things wrong might be useful.

提交回复
热议问题