Java Code for permutations of a list of numbers

后端 未结 4 1399
臣服心动
臣服心动 2020-12-15 11:24

I have written a program to find all the possible permutations of a given list of items. This precisely means that my program prints all possible P(n,r) values for r=0 to n<

相关标签:
4条回答
  • 2020-12-15 11:59

    You do realize that you are generating very large lists, and that running time will increase as the list length does. Have you determined how long the lists that are giving you trouble should be?

    One thing that might help some would be to print each permutation as you find it, instead of gathering them all up into a list and THEN printing them. Of course, if the point is to actually store the whole list, and not just print them, that won't help.

    0 讨论(0)
  • 2020-12-15 12:08

    If you want all permutations of 15-ish or more elements, write them to disk or a db or something, since they won't fit in memory. Edit: Steinhaus–Johnson–Trotter algorithm. This is probably what you're looking for.

    0 讨论(0)
  • 2020-12-15 12:10

    Java library of Google (Guava) has a utility method for this: Collections2#permutations(Collection)

    0 讨论(0)
  • 2020-12-15 12:13

    If you're not storing it -- if you're just iterating through it -- then consider using Heap's algorithm (#3 on http://www.cut-the-knot.org/do_you_know/AllPerm.shtml) -- or, just to make your life easier, use Guava's Collections2.permutations, which doesn't actually construct the whole list of permutations -- it walks through them on the fly. (Disclosure: I contribute to Guava.)

    0 讨论(0)
提交回复
热议问题